如何实现Ant Design Form中两个Form.Item的互斥显隐?
Got it, let's break down how to implement your requirements step by step. The core idea is to use the form's field values to conditionally control each Form.Item's visibility and input disabled state.
Step 1: Retrieve Current Field Values
First, inside your component's render method, grab the current values of the two fields using getFieldValue from the form props:
const { getFieldDecorator, getFieldValue } = this.props.form; const urlValue = getFieldValue('url'); const urlIdValue = getFieldValue('url_id');
Step 2: Toggle Visibility & Disable Input
You have two solid options to handle visibility—pick whichever fits your use case best:
Option A: Conditional Rendering (Unmount When Hidden)
This removes the field from the DOM entirely when it's not needed, which is clean for most scenarios:
{/* Show Url field only if url_id is empty */} {!urlIdValue && ( <Form.Item label="Url"> {getFieldDecorator('url')( <Input disabled={!!urlIdValue} /> {/* Disable if url_id has a value */} )} </Form.Item> )} {/* Show Standaard Urls field only if url is empty */} {!urlValue && ( <Form.Item label="Standaard Urls"> {getFieldDecorator('url_id', {})( this.getSelectUrls() )} </Form.Item> )}
Option B: Hide with CSS (Keep Field in DOM)
If you need to preserve the field's state temporarily (e.g., for quick toggling without losing input), use the style prop to hide it instead:
<Form.Item label="Url" style={{ display: urlIdValue ? 'none' : 'block' }} > {getFieldDecorator('url')( <Input disabled={!!urlIdValue} /> )} </Form.Item> <Form.Item label="Standaard Urls" style={{ display: urlValue ? 'none' : 'block' }} > {getFieldDecorator('url_id', {})( this.getSelectUrls() )} </Form.Item>
Step 3: Auto-Clear Conflicting Values (Optional but Recommended)
To make the user experience smoother, add an onValuesChange handler to the parent Form component. This automatically clears the opposite field when one is filled, preventing conflicting entries:
<Form onValuesChange={(changedValues, allValues) => { if (changedValues.url) { // Clear url_id when url is updated this.props.form.setFieldsValue({ url_id: undefined }); } else if (changedValues.url_id) { // Clear url when url_id is updated this.props.form.setFieldsValue({ url: undefined }); } }} > {/* Your Form.Items go here */} </Form>
How It All Comes Together
- Visibility Control: We check if the opposite field has a value—if it does, we hide the current field (either by not rendering it or using CSS).
- Disabling Logic: The
Urlinput is disabled wheneverurl_idhas a value, fulfilling your first requirement. - Auto-Clear: The
onValuesChangehandler ensures only one field has a value at a time, making the visibility toggle work seamlessly without manual user cleanup.
内容的提问来源于stack exchange,提问作者Spongebob Squarepants




