reactjs - 使用 Ant Design 验证来自父表单的嵌套组件表单项
问题描述
有没有一种方法可以在提交时从其父表单验证嵌套的组件表单项?
这是一个示例,我知道我可以以相同的形式处理这两个项目,这不是将数据从子组件传递到父组件的最佳方式(这只是一个简单的示例来说明我的问题)。我有一个比这个例子更复杂的情况。.
应用程序.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 中的项目?
Ps 我试过props.form
从 App.js 传递给 ChildComponent.js。它没有检查 ChildComponent 项的验证。
解决方案
推荐阅读
- reactjs - 通过history.push渲染组件后触发右滑动画
- ruby - grpc server ruby with TLS/SSL
- salesforce - 将禁用 robohelp 下拉功能的文章导入 Salesforce
- python - 如何在索引号后面显示句点?
- javascript - async/await 会导致代码阻塞吗?异步/等待的实际有用场景是什么?
- c++ - 如何让一个类运行另一个类的功能,反之亦然
- alias - 先前命令字符串替换的 TCSH 别名
- javascript - Vercel 部署的应用程序未在实时版本上进行 API 调用
- r - R:从导入的数据集中提取列的平均值,同时折扣一个值
- javascript - 如何从具有特定字符串匹配的数组中删除项目