如何根据Selector下拉选项切换对应单选按钮组显示
实现下拉选择器与单选按钮组的联动效果
要实现你需要的联动效果,核心是通过状态管理下拉选项的选中值,再根据这个值条件渲染对应的单选按钮组。下面是基于你提供的代码修改后的完整实现:
步骤说明
- 用
useState维护下拉选项的选中状态 - 监听下拉选择器的
onChange事件,更新选中状态 - 根据选中值条件渲染对应的单选按钮组
- 给同一组的单选按钮设置相同的
name属性,保证互斥选中
修改后的完整代码
import { useState } from 'react'; import { Container, Row, Col, Form, Button } from 'react-bootstrap'; const RequestForm = () => { const [validated, setValidated] = useState(false); // 存储下拉选中值的状态 const [selectValue, setSelectValue] = useState(''); const handleSubmit = (event) => { const form = event.currentTarget; if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } setValidated(true); }; // 更新下拉选中值的处理函数 const onChange = (e) => { setSelectValue(e.target.value); }; return ( <Container> <Row> <Form noValidate validated={validated} onSubmit={handleSubmit}> <Row className="mb-3"> <Form.Group as={Col} md="4" controlId="validationCustom01"> <Form.Label>Request Type</Form.Label> <Form.Select onChange={onChange} aria-label="Default select example" value={selectValue} // 绑定选中值,让下拉框受控 > <option value="" disabled> Select Options </option> <option value="1">Leave</option> <option value="2">Salary</option> </Form.Select> </Form.Group> </Row> {/* 根据下拉选中值渲染Leave对应的单选组 */} {selectValue === '1' && ( <div className="mb-3"> <Form.Check label="Half Day" type="radio" name="requestDetail" id="halfDay" /> <Form.Check label="Full Day" type="radio" name="requestDetail" id="fullDay" /> </div> )} {/* 根据下拉选中值渲染Salary对应的单选组 */} {selectValue === '2' && ( <div className="mb-3"> <Form.Check label="50% Salary" type="radio" name="requestDetail" id="halfSalary" /> <Form.Check label="Full Salary" type="radio" name="requestDetail" id="fullSalary" /> </div> )} <Form.Group className="mb-3"> <Form.Check required label="I solemnly affirm that all the details" feedback="You must agree before submitting." feedbackType="invalid" /> </Form.Group> <Button type="submit">Apply</Button> </Form> </Row> </Container> ); }; export default RequestForm;
关键细节说明
- 受控下拉框:给
Form.Select添加value={selectValue},让下拉框成为受控组件,确保状态和UI同步 - 条件渲染:使用
{selectValue === '1' && ...}的语法,只有选中对应值时才渲染目标单选组 - 单选互斥:同一组的单选按钮设置相同的
name属性,保证同一时间只能选中一个选项 - 初始状态优化:将默认选项的
value设为空字符串,避免初始状态与选中值逻辑冲突
内容的提问来源于stack exchange,提问作者Yakuza
相关产品推荐
相关产品推荐

