【问题标题】:How to create a formik form using class components?如何使用类组件创建 formik 表单?
【发布时间】:2021-10-06 13:42:45
【问题描述】:

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

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

我收到以下错误:

钩子只能在函数组件内部调用。

查看Formik lib内部的错误来源,&lt;Formik&gt;似乎是一个函数组件,它在内部调用了useRef钩子。 这是否意味着整个层次结构都需要是功能组件?我发现的所有东西都使用函数组件,但我的代码库已经相当大了...... 提前致谢!

【问题讨论】:

    标签: reactjs formik


    【解决方案1】:

    找到了。 ReactDOM 没有更新,不支持 hooks。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多