乐闻世界logo
搜索文章和话题

How to disable a field in Ant Design React Form?

1个答案

1

In the Ant Design React Form component, disabling fields is a common requirement. This can be achieved by setting the disabled property.

Steps

  1. Use Form.Item: First, ensure that your input components (such as Input, DatePicker, etc.) are wrapped within a Form.Item.
  2. Set the disabled property: Apply the disabled property to your input components. This property accepts a boolean value, where true disables the field and false enables it.

Example Code

Consider a form with a text input field and a date picker. We aim to disable the text input field while keeping the date picker enabled. The code is as follows:

jsx
import React from 'react'; import { Form, Input, DatePicker, Button } from 'antd'; const DemoForm = () => { return ( <Form> <Form.Item label="Username" name="username"> <Input disabled={true} placeholder="Enter username"/> </Form.Item> <Form.Item label="Registration Date" name="registerDate"> <DatePicker disabled={false} /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> ); }; export default DemoForm;

Explanation

In the above example:

  • Username field: We set <Input disabled={true} />, which disables the input field and prevents user interaction.
  • Registration date field: The DatePicker component uses disabled={false}, allowing the user to interact with it normally.

This approach enables you to flexibly enable or disable any form field based on your requirements. Using the disabled property is a straightforward and effective method for controlling input states.

2024年8月9日 20:52 回复

你的答案