[英]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>;
}
}
我收到以下錯誤:
鈎子只能在 function 組件的內部調用。
查看 Formik 庫中的錯誤源,似乎<Formik>
是一個 function 組件,它在內部調用useRef
掛鈎。 這是否意味着整個層次結構需要 function 個組件? 我發現的所有東西都使用 function 組件,但我的代碼庫已經相當大了……提前致謝!
找到了。 ReactDOM 未更新且不支持鈎子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.