在 Forms 中使用 ant design switch

using ant design switch inside Forms

ant design switch里面的正确使用方法是什么,我从官方文档中查不到太多信息。 Switch-Ant Design

下面是我的使用方法。

<Form form={form} layout="vertical">
  <Form.Item
    label="Description"
    name="description"
    rules={[{ required: true, message: 'Enter a description' }]}
  >
    <Input placeholder="Enter Description" />
  </Form.Item>

  <Form.Item name="switch" noStyle valuePropName="checked">
    <Switch checkedChildren="Yes" unCheckedChildren="No" />
    <span>Chargable</span>
  </Form.Item>

  <Button
    onClick={() => {
      form
        .validateFields()
        .then((values) => {
          form.resetFields()
          onCreate(values)
        })
        .catch((info) => {
          console.log('Validate Failed:', info)
        })
    }}
  >
    Save
  </Button>
</Form>

onCreate 不从开关中获取值,而是从描述中获取值

const onCreate = (values) => {}

我猜你的值是 {description: "foo", switch: undefined}?

在我的演示 switch demo 中,我将 initialValue 添加到 Switch,因此当我从表单中获取值时,我得到 {description: "111", switch: true}

不知道你是不是这个意思


或者你可以这样使用

<Form.Item label="foo">         
  <Form.Item name="bar">           
    <Switch />         
  </Form.Item>         
  <span className="ant-form-text">Some text you want</span>       

</Form.Item>

我能够修复它,但执行了以下操作。

<td>
  <Form.Item valuePropName="checked" name="status" noStyle>
    <Switch checkedChildren="Yes" unCheckedChildren="No" />
  </Form.Item>
  <span className="ml-2">Status Enabled</span>
</td>

这是因为在一个 Form.Item 组件中只能有一个子组件。删除 Switch 组件旁边的 span 即可。