在 antd reactjs 中重置 form.fields

reset form.fields in antd reactjs

我正在使用来自 antd 的表单列表 react.js https://ant.design/components/form/#Form.List

我这里有一个简单的表单列表。我可以添加和删除字段。

有时我想重置表格删除我添加的项目

const [form] = Form.useForm();
...
<Form form={form} name="control-hooks">
    <Form.List name="fruits">
        {(fields, { add, remove }) => (
            <>
                {fields.map(({ key, name, ...restField }) => (
                    <Row key={key}>
                        <Col span={24}>
                            <Form.Item {...restField} name={[name, 'color']}>
                                <Select placeholder="Select fruit">{
                                    fruits.map((fruit, index) =>
                                        <Option key={index} value={fruit.color}>
                                            {fruit.color}
                                        </Option>
                                    )
                                }
                                </Select>
                            </Form.Item>
                            <Form.Item {...restField} name={[name, 'quantity']} initialValue={1}>
                                <InputNumber placeholder="Quantity" />
                            </Form.Item>
                            <Button onClick={() => remove(name)}>Remove</Button>
                        </Col>
                    </Row>
                ))}
                <Form.Item>
                    <Button type="dashed" onClick={() => add()}>
                        Add
                    </Button>
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        Submit
                    </Button>
                </Form.Item>
            </>
        )}
    </Form.List>
</Form>
...
<Button type="primary" onClick={resetForm}>Reset from outside</Button>

这是我的尝试:

const resetForm = () => {
  form.resetFields();
}

有什么办法可以做到吗?谢谢

编辑: 我添加了更详细的解释

编辑2

https://codesandbox.io/s/priceless-robinson-6q577?file=/src/index.js

我试着举了一个例子,出于某种原因它奏效了....有什么区别???

编辑3

解决方案:

我找到问题了!这是初始值。如果我的任何 Form.Item 中有 initialValue,antd 将不会删除那些动态添加的字段。感谢帮助

重置函数应使用作为初始值提供的值。

<Form
 ...
        initialValues={{first_name: 'John'}}
/>

如果您想事后更改其中的一些内容,方法是;

form.setFieldsValue({ first_name: 'John' });

为此,您的字段应具有此处定义的名称属性。

<Form.Item
  name="first_name"

Antd Form.List 组件提供了一种在表单中动态添加相同字段的方法。组件的 children 期望像 render prop 一样用作 child 的函数。所以,这个渲染函数将被 antd Form.List 组件调用。我们没有控制 child.

函数的调用

Form.List的children的类型如下。我取自 here.

export interface FormListFieldData {
  name: number;
  key: number;
}

export interface FormListOperation {
  add: (defaultValue?: StoreValue, insertIndex?: number) => void;
  remove: (index: number | number[]) => void;
  move: (from: number, to: number) => void;
}

export interface FormListProps {
 // other types
 children: (
    fields: FormListFieldData[],
    operation: FormListOperation,
    meta: { errors: React.ReactNode[]; warnings: React.ReactNode[] },
  ) => React.ReactNode;
}

因此,我们可以使用children函数中的字段、操作和元数据。


你下面的代码片段,没有做到 Antd Form.List 应该做的。你不是在调用 children 函数,它的 Antd Form.List 组件将使用上面类型片段中提到的一些定义的道具调用 children 函数。

 const [formFields, setFormFields] = useState([]); // you don't need any state.
 ...
 <Form.List>
     {formFields => (  // error, it should be fields that antd expects
       <div>
          {formFields.map(formField => (
          <Form.Item {...formField}>
            <Input />
          </Form.Item>
        ))}
      </div>
     )}
  </Form.List>

下面隐藏了Form.List重置且没有输入的基本示例,请取消隐藏以显示:

// don't run it, it just to hide long snippets
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Space } from 'antd';
import {  PlusOutlined } from '@ant-design/icons';

const Demo = () => {
  const [form] = Form.useForm();
  const onFinish = values => {
    console.log('Received values of form:', values);
    
  };

  const onReset = () => {
    form.resetFields()
  }

  return (
    <Form form={form} name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
      <Form.List name="hello">
        {(fields, { add }) => (
          <>
            {fields.map(({ key, name,  }) => (
              <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                <Form.Item
                 
                  name={[name, 'first']}
                  rules={[{ required: true, message: 'Missing first name' }]}
                >
                  <Input placeholder="First Name" />
                </Form.Item>
                <Form.Item
                 
                  name={[name, 'last']}
                  rules={[{ required: true, message: 'Missing last name' }]}
                >
                  <Input placeholder="Last Name" />
                </Form.Item>
              </Space>
            ))}
            <Form.Item>
              <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                Add field
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
        <Button type="secondary" onClick={onReset}>
          Reset
        </Button>
      </Form.Item>
    </Form>
  );
};

ReactDOM.render(<Demo />, document.getElementById('container'));
// dont run it

form.resetFields() 将清除输入值并从表单中删除输入,如果 Form.list 有一个与之关联的名称 property/attribute。

你能试试这个吗?

form.setFieldsValue({ fruits:[] });