React中如何实现复选框互斥(可全不选)的映射逻辑
解决每行独立的互斥复选框问题
你的核心问题是全局状态导致所有行的复选框联动——当前checkedTable和checkedSkip是组件级的全局状态,修改任何一行的复选框都会让所有行跟着变化。要实现每行两个复选框独立互斥(选一个时另一个自动取消,同时允许都不选),需要给每行单独维护状态。
解决方案步骤:
- 用对象状态存储每行的选择:键为
question,值可选'table'、'skip'或null(null表示都不选) - 统一处理复选框的变更逻辑,根据当前点击的类型和已有状态,决定是选中还是取消
- 渲染时根据每行的状态判断复选框是否选中
修改后的完整代码:
import Table from 'react-bootstrap/Table'; import { useState } from "react"; function myfunc() { // 用对象存储每行的选中状态,键是question,值为'table'/'skip'/null const [selectedOptions, setSelectedOptions] = useState({}); const handleOptionChange = (question, type) => { setSelectedOptions(prev => { // 如果当前已经选中该类型,点击就取消(设为null) if (prev[question] === type) { return { ...prev, [question]: null }; } // 否则选中当前类型,自动取消另一个 return { ...prev, [question]: type }; }); }; return ( <Table style={{width: "100%"}} striped> <thead> <tr> <th>QNAME</th> <th>Table</th> <th>Fills/Skips</th> </tr> </thead> <tbody> {typeof questions === 'undefined' ? ( <p>Loading...</p> ) : ( questions.map((question, i) => ( <tr key={i}> <td>{question}</td> <td> <input type="checkbox" name={question} id={`${question}-table`} checked={selectedOptions[question] === 'table'} onChange={() => handleOptionChange(question, 'table')} /> </td> <td> <input type="checkbox" name={question} id={`${question}-skip`} checked={selectedOptions[question] === 'skip'} onChange={() => handleOptionChange(question, 'skip')} /> </td> </tr> )) )} </tbody> </Table> ); } export default myfunc;
逻辑说明:
- 点击一个复选框时,如果它已经是选中状态,就把该行的状态设为
null(两个都不选) - 如果它未选中,就把该行状态设为对应的类型,自动覆盖之前的
skip或table状态,实现互斥 - 每行的状态独立存储,不会影响其他行
内容的提问来源于stack exchange,提问作者MotoMatt5040
相关产品推荐
相关产品推荐

