我使用 Ant Design 的 Form 和 Radio.Group 组件来创建一个包含两个单选组的表单:
import React, { useState } from 'react';
import { Form, Radio } from 'antd';
const MyComponent = () => {
const [form] = Form.useForm();
const [gender, setGender] = useState<boolean>(true); // true = Male, false = Female
const handleGenderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setGender(e.target.value); // Update gender based on selection
};
return (
<Form form={form}>
{/* Gender Selection */}
<p className="font-bold text-l pl-3">Gender:</p>
<Form.Item
name="gender"
rules={[{ required: true, message: 'Please select your gender!' }]}
>
<Radio.Group onChange={handleGenderChange} value={gender}>
<Radio value={true}>Male</Radio>
<Radio value={false}>Female</Radio>
</Radio.Group>
</Form.Item>
{/* Preferred Gender (Disabled) */}
<p className="font-bold text-l pl-3">Preferred Gender:</p>
<Form.Item name="preferredGender">
<Radio.Group value={!gender} disabled>
<Radio value={true}>Male</Radio>
<Radio value={false}>Female</Radio>
</Radio.Group>
</Form.Item>
{/* Submit Button */}
<Form.Item>
<button type="submit">Submit</button>
</Form.Item>
</Form>
);
};
export default MyComponent;
如何让第二个Radio.Group自动选择与第一个相反的选项?
使用
form.setFieldValue
Antd hook 然后您可以在每次 useEffect
更改时使用 gender
更新您的状态:
useEffect(() => {
form.setFieldValue("preferredGender", !gender);
}, [gender]);