蚂蚁设计<Form.List>创建表格的静态数组

时间:2020-03-06 09:38:40

标签: reactjs typescript antd

我正在将antdreact结合使用来开发应用程序。

<Form.List name="secondaryContacts">
  {(fields, { add, remove }) => {
    return (
      <div>
        {fields.map((field, index) => (
          <Form.Item
            {...formItemLayoutWithOutLabel}
            label={index === 0 ? "" : ""}
            required={false}
            key={field.key}
          >
            <Form.Item
              {...field}
              validateTrigger={["onChange", "onBlur"]}
              rules={[
                {
                  required: true,
                  validator: phoneNumberValidator
                }
              ]}
            >
              <Input
                placeholder="Secondary Contact"
                addonAfter={
                  fields.length >= 1 ? (
                    <MinusCircleOutlined
                      onClick={() => {
                        remove(field.name);
                      }}
                    />
                  ) : null
                }
              />
            </Form.Item>
          </Form.Item>
        ))}
        <Form.Item {...formItemLayoutWithOutLabel}>
          <Button
            type="dashed"
            onClick={() => {
              add();
            }}
            style={{ width: "100%" }}
          >
            <PlusOutlined /> Add Secondary Contact
          </Button>
        </Form.Item>
      </div>
    );
  }}
</Form.List>;

上面是我用来添加动态表单字段并使用Form.List进行验证的代码。

现在我有一个特定的场景,我需要为所选的time slot显示7个Sliders(https://ant.design/components/slider/)并将它们存储在一个数组中,所以我考虑使用Form.List并保留里面的所有滑块都和上面一样(除了它是静态的)。

但是我不清楚如何使用Form.List 来实现它,互联网上的例子很少。

我有一个场景,我需要一个表单数组,并使用Form.List将它们合并为一个数组。

2 个答案:

答案 0 :(得分:0)

您仍然需要<Form>组件

尝试

<Form>
  <Form.List>
  </Form.List>
</Form>

答案 1 :(得分:0)

您可以使用 initialValue 属性设置静态数据

示例:

const staticValue = [{ formItem1: 'value1', formItem2: 'value2'}];
    
<Form.List name="formListName" initialValue={staticValue}>
   {(fields, { add, remove }, { errors }) => (
      <Form.Item {...field} name={[field.name, "formItem1"]}>
         <Input placeholder="Field 1" />
      </Form.Item>
  .....
相关问题