
本文详解如何在 react 问卷组件中正确管理多个独立单选题(radio button)的状态,避免题目间选项互相干扰,并实现每题答案的精准绑定与持久化。
本文详解如何在 react 问卷组件中正确管理多个独立单选题(radio button)的状态,避免题目间选项互相干扰,并实现每题答案的精准绑定与持久化。
在构建 React 问卷应用时,一个常见却易被忽视的问题是:不同题目共用相同 name 属性或状态判断逻辑错误,导致切换题目后前一题的选择“残留”到下一题。这并非 React 的 Bug,而是因 radio 按钮的 checked 属性未与当前题目的实际选中值严格对齐所致。
核心问题在于你原始代码中的这一行:
checked={selectedOptions[item.soal[currentSoal].id === opsiItem.id]}
该表达式语法错误(=== 是比较运算符,不能用于对象属性访问),且逻辑混乱——它试图将布尔结果 true/false 当作 key 去查 selectedOptions,必然返回 undefined,导致所有 radio 默认未选中或意外全部选中。
✅ 正确做法是:为每道题生成唯一、稳定、可复用的 name 字符串(如 "soal[123]"),并确保 checked 精确比对 selectedOptions[name] === 当前选项 id。
KeystoneJS 是一个功能强大的开源无头 CMS,适用于 Node.js,它根据您的模式定义自动生成 GraphQL API 和基于 React 的管理界面。由 Thinkmill 构建,支持 PostgreSQL 和 SQLite、自定义访问控制、钩子、虚拟字段和基于文档的富文本编辑。
以下是经过生产验证的完整实现方案:
✅ 正确的状态结构与渲染逻辑
import React, { useState } from 'react';
const QuizComponent = ({ questions }) => {
const [currentSoal, setCurrentSoal] = useState(0);
// state 结构示例:{ "soal[101]": "opt-456", "soal[102]": "opt-789" }
const [selectedOptions, setSelectedOptions] = useState({});
const handleOptionChange = (event) => {
const { name, value } = event.target;
setSelectedOptions(prev => ({
...prev,
[name]: value
}));
};
const handleNextQuestion = () => {
if (currentSoal prev + 1);
}
};
const currentQuestion = questions[currentSoal];
const questionName = `soal[${currentQuestion.id}]`; // 唯一标识,对应 Laravel Blade 的命名习惯
return (
<div classname="quiz-container">
<h3 classname="text-lg font-semibold mb-4">第 {currentSoal + 1} 题:{currentQuestion.text}</h3>
<div classname="space-y-3">
{currentQuestion.opsi.map((option, idx) => (
<label key="{option.id}" classname="flex items-center p-3 rounded-lg hover:bg-gray-50 cursor-pointer transition-colors">
<input type="radio" name="{questionName}" value="{option.id}" checked option.id onchange="{handleOptionChange}" classname="h-4 w-4 text-blue-600 focus:ring-blue-500"><span classname="ml-3 text-gray-700">{option.opsi}</span>
</label>
))}
</div>
<div classname="mt-6 flex justify-between">
<button onclick="{()"> currentSoal > 0 && setCurrentSoal(prev => prev - 1)}
disabled={currentSoal === 0}
className="px-4 py-2 text-gray-600 disabled:opacity-50"
>
上一题
</button>
<button onclick="{handleNextQuestion}" disabled>= questions.length - 1}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{currentSoal === questions.length - 1 ? '提交答卷' : '下一题'}
</button>
</div>
</div>
);
};
export default QuizComponent;
? 关键要点说明
-
name必须唯一且稳定:使用soal[${question.id}]格式(而非仅question.id),既兼容 Laravel 后端接收习惯,又避免 ID 冲突风险; -
checked判断必须严格相等:selectedOptions[questionName] === option.id—— 这是防止跨题污染的唯一防线; -
状态更新推荐函数式写法:
setSelectedOptions(prev => ({...prev, [name]: value})),避免闭包旧值问题; -
无需重置
selectedOptions:每题独立 key,天然隔离;用户回退时历史选择自动恢复; -
无障碍友好:每个
包裹,点击文字即可触发选择。
⚠️ 常见陷阱规避清单
| 错误写法 | 后果 | 正确写法 |
|---|---|---|
name={currentQuestion.id} |
多题 ID 相同时 radio 组互斥失效 |
name={soal[${currentQuestion.id}]}
|
checked={selectedOptions[currentQuestion.id] === option.id} |
key 不匹配,始终为 false
|
checked={selectedOptions[soal[${currentQuestion.id}]] === option.id}
|
checked={option.id === selectedOptions?.[questionName]} |
可选链在 falsy 值下可能误判 | 直接 === 比较(undefined === id → false,安全) |
使用 defaultChecked 替代 checked
|
无法响应状态更新,失去受控性 | 始终使用 checked + onChange 构成受控组件 |
通过以上实现,你将获得一个完全受控、题目间零干扰、支持任意跳转、语义清晰且可无障碍访问的 React 问卷单选系统。状态即真理,key 即契约 —— 把握这两点,Radio 同步问题迎刃而解。










