【问题标题】:Ant design <Form.List> create static array of formsAnt design <Form.List> 创建表单的静态数组
【发布时间】:2020-03-06 09:38:40
【问题描述】:

我正在使用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 个滑块(https://ant.design/components/slider/)并将它们存储在一个数组中,所以我想使用 Form.List 并将所有滑块保留在里面,就像上面一样(除了它是静态的)。

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

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

【问题讨论】:

  • 你面临什么困难?
  • 无法为静态项目集添加 form.list 条目。
  • 问题解决了吗?

标签: reactjs typescript antd


【解决方案1】:

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

例子:

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

【讨论】:

    【解决方案2】:

    你还需要&lt;Form&gt;组件

    试试

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2021-12-14
      • 1970-01-01
      • 2021-06-12
      相关资源
      最近更新 更多