React - 将 Formik 函数组件迁移到 class 个组件

React - Migrate Formik Function components to class Components

我是 React 的新手,开始使用基于 class 的组件。我最终将 Formik and i am having trouble converting a function based component example 用于基于 class 的。下面是我正在尝试转换的示例。

const MyTextInput = ({ label, ...props }) => {
  // useField() returns [formik.getFieldProps(), formik.getFieldMeta()]
  // which we can spread on <input> and alse replace ErrorMessage entirely.
  const [field, meta] = useField(props);
  return (
    <>
      <label htmlFor={props.id || props.name}>{label}</label>
      <input className="text-input" {...field} {...props} />
      {meta.touched && meta.error ? (
        <div className="error">{meta.error}</div>
      ) : null}
    </>
  );
};

我完成了所有渲染部分,但在

方面遇到了问题
{ label, ...props } // How do i extract this?

const [field, meta] = useField(props); // Hooks are not allowed in class based components

React 显然不允许在基于 class 的组件中使用 Hooks。感谢任何帮助。

谢谢。

在 class 方法上,您的字段如下:

class MyTextInput extends React.Component {
  handleChange = value => {
    const { name, onChange } = this.props;
    onChange(name, value.target.value);
  };

  handleBlur = () => {
    const { name, onBlur } = this.props;
    if (onBlur) {
      onBlur(name, true);
    }
  };
  render() {
    const { label, touched, errors, id, name, value, ...attributes } = this.props;
    const err = getIn(errors, name);
    const touch = getIn(touched, name);
    return (
      <>
        <label htmlFor={id || name}>{label}</label>
        <Field
        {...attributes}
        name={name}
        value={value || ''}
        className="text-input"
        onChange={this.handleChange}
        onBlur={this.handleBlur}
        />
        {touch && err ? <div className="error">{err}</div> : null}
      </>
    );
  }
}

formik字段:

const SignupForm = () => {
  return (
    <>
      <h1>Subscribe!</h1>
      <Formik
        ...
      >
        {({ setFieldValue, setFieldTouched, values, errors, touched }) => (
          <Form>
            <MyTextInput
              label="First Name"
              name="firstName"
              errors={errors}
              touched={touched}
              value={values.firstName}
              onChange={setFieldValue}
              onBlur={setFieldTouched}
              placeholder="Jane"
            />
            <MyTextInput
              label="Last Name"
              name="lastName"
              type="text"
              placeholder="Doe"
            />
            <MyTextInput
              label="Email Address"
              name="email"
              type="email"
              placeholder="jane@formik.com"
            />
            <button type="submit">Submit</button>
          </Form>
        )}
      </Formik>
    </>
  );
};