简体   繁体   中英

How to create a formik form using class components?

I want a generic form wrapper and generic field wrappers. I have these files:

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

and for Field

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

And I would like them to be used like so:

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

I'm getting the following error:

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

Looking at the error origin inside the Formik lib, it appears <Formik> is a function component, which internally calls the useRef hook. Does this mean that the entire hierarchy need to be function components? Everything I found uses function components, but my codebase is already pretty big... Thanks in advance!

Found it. ReactDOM was not updated and did not support hooks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM