首页 > 解决方案 > 使用 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 项的验证。

标签: reactjsformsantdant-design-pro

解决方案


推荐阅读