React动态问卷中RadioButton选择异常问题排查与修复
问题根源
你判断的完全正确——问题出在name属性重复上。浏览器会把拥有相同name值的radio按钮划分为同一组,所以不同卡片里的radio会互相干扰,出现跨卡片选中、点击无响应却触发第一张卡片选项的情况。
修复方案
给每个问卷卡片的radio组生成唯一的name值,可以结合问卷的ID、循环索引等唯一标识来拼接:
代码修改示例
假设你原代码类似这样(存在问题的写法):
{questions.map(question => ( <div className="card"> {question.options.map(option => ( <label> <input type="radio" name="question-option" // 所有radio共用同一个name,导致分组混乱 value={option.value} checked={selectedValue === option.value} onChange={(e) => handleChange(e)} /> {option.label} </label> ))} </div> ))}
修改为以下写法,用问卷唯一标识生成专属name:
{questions.map((question, idx) => ( <div className="card" key={question.id || idx}> {question.options.map(option => ( <label key={option.value}> <input type="radio" name={`question-${question.id}-options`} // 用question.id拼接出唯一name value={option.value} checked={selectedAnswers[question.id] === option.value} onChange={(e) => handleChange(e, question.id)} /> {option.label} </label> ))} </div> ))}
配套状态调整
如果之前用单个变量存储选中值,会导致所有问卷共享状态,需要改成对象形式:
// 初始化状态 const [selectedAnswers, setSelectedAnswers] = useState({}); // 处理选中逻辑 const handleChange = (e, questionId) => { setSelectedAnswers(prev => ({ ...prev, [questionId]: e.target.value })); };
内容的提问来源于stack exchange,提问作者aetosti
相关产品推荐
相关产品推荐

