使用 getFieldValue() 保存多种形式的数据

IT技术 javascript reactjs
2021-05-02 19:09:15

我尝试将数据从2表(保存MainSubForm使用)getFieldValue()这里应该出现两个表单数据:

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

现在,当我单击save处理程序时,我得到一个空对象如果我<SubForm/>从主表单中删除i get 值,但是如果我再次添加第二个表单,我将无法从两个表单中获取数据。,br> 如何获取数据,点击保存按钮,从两种形式使用getFieldValue()
演示: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>

1个回答

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

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

并在各自的表格上设置这些参考

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

<SubForm myRef={subFormRef} />

最后,在save函数内部,调用getFieldValue两个 refs

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