Реагировать - перенести компоненты Formik Function в класс Components - PullRequest
0 голосов
/ 02 марта 2020

Я новичок в 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, по-видимому, не позволяет использовать хуки в компонентах на основе классов. Любая помощь приветствуется.

Спасибо.

1 Ответ

1 голос
/ 04 марта 2020

На методах класса ваше поле будет выглядеть так:

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