使用 getFieldValue() 保存多种表单中的数据

2024-03-06

我尝试保存 2 个表单中的数据(Main and SubForm) using getFieldValue()。这里应该出现两个表单数据:

const save = () => {
    console.log(myRef.current.getFieldValue());
};

现在,当我单击时,我得到一个空对象save处理程序。如果我删除<SubForm/>我从主表单中获取值,但是如果我再次添加第二个表单,我无法从两个表单中获取数据。 ,br> 如何通过单击保存按钮从两种表单中获取数据getFieldValue()?
demo: https://codesandbox.io/s/dazzling-ganguly-vz7o7?file=/src/OuterForm.js https://codesandbox.io/s/dazzling-ganguly-vz7o7?file=/src/OuterForm.js


我的代码的一部分:

     <Form
        name="main"
        ref={myRef}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        id="ma"
        form={form}
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input.Password />
        </Form.Item>
      </Form>
      <SubForm myRef={myRef} />
      <button onClick={save}>save</button>
    </div>

您需要定义 2 个引用,每个表单一个。

const mainFormRef = useRef();
const subFormRef = useRef();

并在相应的表单上设置这些引用

<Form
  name="main"
  ref={mainFormRef}
  ....
>
  ....
</Form>

<SubForm myRef={subFormRef} />

最后,在里面save函数、调用getFieldValue在两个裁判上

const save = () => {
    console.log(mainFormRef.current.getFieldValue());
    console.log(subFormRef.current.getFieldValue());
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 getFieldValue() 保存多种表单中的数据 的相关文章

随机推荐