首页 > 解决方案 > 在 handleChange Typescript 中传递值

问题描述

在我在网上看到的所有示例中,只有事件被传递到 handleChange 并且值被自动使用。但是,我收到一个错误,即找不到值。如何在 handleChange 中使用值?我正在尝试在此处使用 Formik 验证表单。

export default function MyPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved, setIsRemoved] = useState(false);

  const [removeUser] = useMutation<Response>(USER);

  let submitForm = (email: string) => {
    User({
      variables: {
        email: email,
      },
    })
      .then(({ data }: ExecutionResult<Response>) => {
        if (data !== null && data !== undefined) {
          setIsRemoved(true);
        }
      })  };

  const formik = useFormik({
    initialValues:{ email: '' },
    onSubmit:(values, actions) => {
       setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
          }, 1000);
        },
       validationSchema:schema
    })

    const handleChange = (e: ChangeEvent<HTMLInputElement>)=>{
      if (name!== null) && (value!==null){
      const {name,value} = event.target;
      formik.setFieldValue(name,value);
      }
     }

  return (
    <div>
              <Form
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(formik.values.email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={formik.touched.email ? formik.errors.email : ''}
                    error={formik.touched.email && Boolean(formik.errors.email)}
                    label="Email"
                    value={formik.values.email}
                    //onChange={change.bind(null, 'email')}
                    onChange={handleChange}
                  />
                  <CustomButton
                    disabled={!isValid || !formik.values.email}
                    text={'Remove User'}
                  />
                </div>
              </Form>
    </div>
  );
}

在这条线上:

const {name,value} = event.target;

即使我已经用 if 语句检查了这个错误,我也会收到这个错误:

Property 'name' does not exist on type 'EventTarget | null'.ts(2339)

标签: javascriptreactjstypescriptmaterial-uiformik

解决方案


您正在尝试访问尚未分配的值。首先,声明它们然后尝试访问它们。此外,您正在使用event.target但您需要使用e.target,因为您已声明事件,例如:

 const handleChange = (e: ChangeEvent<HTMLInputElement>)

因此,函数内部的代码handleChange()需要更新如下:

 const { name,value } = e.target;
 if (name && value){
    formik.setFieldValue(name, value);
 }

推荐阅读