React-Bootstrap动态表格中行内单选按钮无法互斥选中如何解决
问题核心原因
单选按钮无法互斥的核心是你没有给所有单选按钮设置相同的name属性,同时建议用受控组件的写法绑定选中状态,避免出现视图和状态不同步的异常。
实现方案
- 先新增一个state用来存储当前选中的entity值:
const [selectedEntity, setSelectedEntity] = useState('');
- 修改你的Table渲染逻辑,给所有
Form.Check组件添加相同的name属性,同时绑定checked和onChange属性即可:
<Table striped bordered style={{ color: "#4d4d4d" }}> <thead> <tr> <th>Entities</th> </tr> </thead> <tbody> {entities.map(entity => <tr key={entity} style={{ color: "#4d4d4d" }}> <td> <Row> <Col> <Form.Check type="radio" name="entitySelectGroup" label={entity} checked={selectedEntity === entity} onChange={() => setSelectedEntity(entity)} /> </Col> </Row> </td> </tr>)} </tbody> </Table>
补充说明
该方案不需要额外包裹Form组件,不会破坏表格的DOM结构导致渲染异常,既能实现单选互斥的效果,也可以直接通过selectedEntity拿到当前选中的结果。
内容的提问来源于stack exchange,提问作者KilledByCheese
相关产品推荐
相关产品推荐

