简体   繁体   English

在 Ant 设计表单中显示无线电选项的自定义消息

[英]Display custom messages for radio options in Ant Design form

I'm using Radio.Group in Ant Design form and depending on the option I would like to display a custom message below.我在 Ant 设计表单中使用 Radio.Group,根据选项我想在下面显示自定义消息。 I'm trying to use form.getFieldValue() and my code looks like this, but it doesn't work.我正在尝试使用form.getFieldValue()并且我的代码看起来像这样,但它不起作用。 How can I fix it?我该如何解决?

const options = [
  {
    value: 1,
    label: "Option 1"
  },
  {
    value: 2,
    label: "Option 2"
  }
];

const Demo = () => {
  const [form] = Form.useForm();
  const { getFieldValue } = form;

  return (
    <Form
      form={form}
      initialValues={{
        radio: 1
      }}
    >
      <Form.Item
        label="Radio Group"
        name="radio"
      >
        <Radio.Group options={options} />
      </Form.Item>
      {getFieldValue("radio") === 1 && <div>This is option 1</div>}
      {getFieldValue("radio") === 2 && <div>This is option 2</div>}
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

Here is my codesandbox .这是我的代码框

I think it's will help you to understand我想这会帮助你理解

const Demo = () => {
  const [form] = Form.useForm();
  const { getFieldValue, validateFields } = form;
  const [radioValue, setRadioValue] = useState(1);
  const onValidateForm = async () => {
    const value = await validateFields();
    window.alert(JSON.stringify(value, 2));
  };

  return (
    <Form
      {...layout}
      form={form}
      name="basic"
      initialValues={{
        radio: 1
      }}
    >
      <Form.Item label="Options" name="radio">
        <Radio.Group options={options} onChange={e => setRadioValue(e.target.value)} />
      </Form.Item>
      {radioValue === 1 && <div>This is option 1</div>}
      {radioValue === 2 && <div>This is option 2</div>}
      <Form.Item>
        <Button type="primary" htmlType="submit" onClick={onValidateForm}>
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM