【问题标题】:How to set value in MUI Select on onChange in Formik?如何在Formik的onChange上设置MUI Select的值?
【发布时间】:2022-08-13 02:37:28
【问题描述】:

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

    标签: reactjs material-ui formik yup formik-material-ui


    【解决方案1】:

    在这里,我直接使用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>
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 2022-01-18
      • 2019-07-06
      • 2022-11-20
      • 2021-10-17
      相关资源
      最近更新 更多