簡體   English   中英

React - 將 Formik 函數組件遷移到類組件

[英]React - Migrate Formik Function components to class Components

我是 React 的新手,從基於類的組件開始。 我最終使用了Formik ,但在將基於函數的組件示例轉換為基於類的示例時遇到了問題。 下面是我正在嘗試轉換的示例。

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 顯然不允許在基於類的組件中使用 Hook。 任何幫助表示贊賞。

謝謝。

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

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>
    </>
  );
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM