如何使用 class 组件创建 formik 表单?

How to create a formik form using class components?

我想要通用表单包装器和通用字段包装器。我有这些文件:

import React, { Component } from "react";
import pComponent from "pComponent";
import { Formik, Form } from "formik";
import { object, func, elementType, any, bool, oneOfType } from "prop-types";


export default class PL_Form extends Component {

  render() {
    let { children, onSubmit, initialValues, ...otherProps } = props;
    
    return (
      <Formik onSubmit={onSubmit} initialValues={initialValues} {...otherProps}>
        <Form>
          {children}
        </Form>
      </Formik>
    );
  }
}

和字段

import React from "react";
import pComponent from "pComponent";
import { Field } from "formik";
import classNames from 'classnames';
import ValidationError from "./ValidationError";

export default class MyField extends pComponent {

    render() {
    let { name, fieldProps, component, className, fieldClassName, ...otherProps } = this.props;
    return (
      <Field name={name} id={name} className={fieldClassName} {...otherProps}>
        {
          (props) => {
            const { field, form, meta } = props;
            return (
              <this.props.component 
                {...field}
                {...fieldProps}
                form={form}
                meta={meta}
                className={classNames(this.props.className, { invalid: meta.error && meta.touched })}
              >
                <ValidationError {...meta} />
              </this.props.component>
            );
          }
        }
      </Field>
    );
  }
}

我希望它们能像这样使用:

import React from "react";
import MyForm from "./Form";
import MyTextField from "./TextField";

export default class TestComponent extends React.Component {
  constructor(props) {
    super(props);

    this.initialValues = {
      name: "",
      pw: ""
    };
  }

  render() {
    return <MyForm onSubmit={console.log} initialValues={this.initialValues}>
      <MyTextField name="name"/>
      <MyTextField name="pw"/>
    </MyForm>;
  }
}

我收到以下错误:

Hooks can only be called inside the body of a function component.

查看Formik lib中的错误来源,似乎<Formik>是一个函数组件,它内部调用了useRef hook。 这是否意味着整个层次结构都需要是功能组件?我找到的所有东西都使用函数组件,但我的代码库已经相当大了…… 提前致谢!

找到了。 ReactDOM 未更新且不支持 hooks。