TypeError: Cannot read property 'setFieldValue' of undefined. Formik doesn't recognise setFieldValue

TypeError: Cannot read property 'setFieldValue' of undefined. Formik doesn't recognise setFieldValue

我正在尝试在我的表单上创建图片上传。问题是当我尝试将值更改为实际上传的文件时。我正在尝试使用 setFieldValue,但它说它未定义。下面是代码。任何想法为什么它是未定义的?我以为是 Formik 自带的。

import { Formik } from 'formik';


const AddProduct = (props) => {

  return (
    <Formik
      initialValues={{
        serviceImage: null
      }}
      
      onSubmit={(values) => {
        console.log(values);
        
      }}
    >
      {({
        errors,
        handleBlur,
        handleChange,
        handleSubmit,
        setFieldValue,
        isSubmitting,
        touched,
        values,
        formProps
      }) => (
        <form onSubmit={handleSubmit}>
          <TextField
            error={Boolean(touched.serviceName && errors.serviceName)}
            fullWidth
            helperText={touched.serviceName && errors.serviceName}
            label="Service name"
            margin="normal"
            name="serviceName"
            onBlur={handleBlur}
            onChange={handleChange}
            value={values.serviceName}
          />

          <Button>
            <input
              id="file"
              name="serviceImage"
              value={values.serviceImage}
              type="file"
              onChange={(event) => formProps.setFieldValue('serviceImage', event.target)
              }
            />
            Add an Image
          </Button>

            <Button
              type="submit"            >
              Post this service on the Events Platform
            </Button>
        </form>
        
      )}
    </Formik>
  );
};

您已经在您的 formik 回调函数中声明了 setFieldValue

所以改成:

<input
  id="file"
  name="serviceImage"
  value={values.serviceImage}
  type="file"
  onChange={event => setFieldValue('serviceImage', event.currentTarget.files[0])}
/>;