【发布时间】: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内部的错误来源,<Formik>似乎是一个函数组件,它在内部调用了useRef钩子。
这是否意味着整个层次结构都需要是功能组件?我发现的所有东西都使用函数组件,但我的代码库已经相当大了......
提前致谢!
【问题讨论】: