繁体   English   中英

如何在 Formik 的 onChange 上设置 MUI Select 中的值?

[英]How to set value in MUI Select on onChange in Formik?

我在将Formik与 MUI 的Select组件集成时遇到了一些挑战,首先,它没有改变onChange事件的值,也没有显示任何错误消息,如果我没有 select 任何东西,所以最后,我能够找到解决方案,我在下面分享了答案

在这里,我直接使用formik.setFieldValue设置值并将值传递给我们通常做的,也显示错误消息我使用了来自 MUI 的FormHelperText

 const formik = useFormik({
      initialValues: {
         user: '',
      },
      validationSchema: validationSchema,
      onSubmit: (values) => {
         alert(JSON.stringify(values, null, 2));
      },
   });

------------


 <FormControl
               fullWidth
               size="small"
               id="userType"
               error={formik.touched.userType && Boolean(formik.errors.userType)}
            >
               <InputLabel id="user-type">User Type</InputLabel>
               <Select
                  id="userType"
                  label="User Type"
                  name="userType"
                  value={formik.values.userType}
                  onBlur={formik.handleBlur}
                  onChange={(e) => formik.setFieldValue('userType', e.target.value as string)}
                  error={formik.touched.userType && Boolean(formik.errors.userType)}
               >
                  <MenuItem value={'admin'}>Student</MenuItem>
                  <MenuItem value={'superAdmin'}>Recruiter</MenuItem>
               </Select>
               {formik.touched.password && (
                  <FormHelperText sx={{ color: 'error.main' }}>{formik.errors.userType}</FormHelperText>
               )}
            </FormControl>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM