有没有办法可以在提交时从其父表单验证嵌套组件表单项?
这是一个例子,我知道我可以以相同的形式处理这两个项目,但这不是将数据从子组件传递到父组件的最佳方法(这只是一个简单的例子来说明我的问题)。我的情况比这个例子更复杂。.
应用程序.js
import React from "react";
import { FormComponentProps } from "antd/lib/form/Form";
import { Input, Form } from "ant";
import ChildComponent from "./ChildComponent";
function App() {
const [state, setState] = React.useState("");
const [childValue, setChildValue] = React.useState("");
const handleSubmit = e => {
e.preventDefault();
props.form.validateFields((err, values) => {
if (!err) {
console.log(state);
console.log(childValue);
}
});
};
const { getFieldDecorator } = props.form;
return (
<Form onSubmit={handleSubmit}>
<Form.Item
label="Name"
labelAlign="left"
colon={false}
labelCol={{ span: 8 }}
wrapperCol={{ span: 14 }}
required={false}
>
{getFieldDecorator("name", {
rules: [
{
required: true
}
]
})(
<Input
type="text"
name="Name"
onChange={e => setState(e.target.value)}
/>
)}
</Form.Item>
<ChildComponent setChildValue={setChildValue} />
</Form>
);
}
const WrappedApp = Form.create({ name: "App" })(App);
export default WrappedApp;
ChildComponent.js
import React, { useEffect } from "react";
import { Input, Form } from "antd";
function ChildComponent(props) {
const [state, setState] = React.useState("");
useEffect(() => {
props.setChildValue(state);
}, [state]);
const { getFieldDecorator } = props.form;
return (
<Form.Item
label="Last"
labelAlign="left"
colon={false}
labelCol={{ span: 8 }}
wrapperCol={{ span: 14 }}
required={false}
>
{getFieldDecorator("last", {
rules: [
{
required: true
}
]
})(
<Input
type="text"
name="Last"
onChange={e => setState(e.target.value)}
/>
)}
</Form.Item>
);
}
export default ChildComponent;
当我从 App.js 提交表单时,我还想检查 ChildComponent.js 中项目的验证。 有没有办法可以传递 App.js 表单中的引用来验证 ChildComponent 中的项目?
P.s. 我尝试将
props.form
从 App.js 传递到 ChildComponent.js。它没有检查 ChildComponent 项的验证。
有点晚了,但是如果您在子组件的 props 中传递了表单,那么您根本不需要执行 setChildValue,并且在处理提交时将捕获子表单值的值。 所以:
<ChildComponent form={form} />
那么孩子和父母都应该得到验证。