
本文详解 react 中多题单选按钮(radio button)状态隔离的关键实现:通过统一 state 管理 + 唯一 name 命名 + 严格 checked 判断,确保每道题的选项互不干扰。
本文详解 react 中多题单选按钮(radio button)状态隔离的关键实现:通过统一 state 管理 + 唯一 name 命名 + 严格 checked 判断,确保每道题的选项互不干扰。
在构建 React 问卷应用时,一个常见却容易被忽视的问题是:切换题目后,下一道题的单选按钮自动“继承”上一题的选择状态。这并非浏览器缓存或 React 渲染 bug,而是由于 radio 按钮的 name 属性未唯一标识题目,且 checked 属性判断逻辑存在缺陷——导致多个题目共用同一组 name,React 将其视为同一组互斥选项。
核心问题在于你原始代码中的两个关键错误:
-
name值重复且无上下文隔离name={item.soal[currentSoal].id} // ❌ 仅用 question.id,不同题可能重名;且未体现“soal”语义应改为语义化、唯一化的命名格式,如
soal[123],与 Laravel Blade 中name="soal[{{ $question->id }}]"对齐,确保每道题拥有独立的 radio 组。 -
checked判断逻辑错误checked={selectedOptions[item.soal[currentSoal].id === opsiItem.id]} // ❌ 语法错误 + 逻辑颠倒这行代码实际执行的是
selectedOptions[true]或selectedOptions[false],完全无法读取正确值。正确写法应为:
KeystoneJS 无头 CMS,带有 GraphQL API 和 React 管理界面下载KeystoneJS 是一个功能强大的开源无头 CMS,适用于 Node.js,它根据您的模式定义自动生成 GraphQL API 和基于 React 的管理界面。由 Thinkmill 构建,支持 PostgreSQL 和 SQLite、自定义访问控制、钩子、虚拟字段和基于文档的富文本编辑。
checked={selectedOptions[`soal[${item.soal[currentSoal].id}]`] === opsiItem.id}
✅ 正确实现如下(含完整可运行结构):
import React, { useState } from 'react';
const QuizComponent = ({ questions }) => {
const [currentSoal, setCurrentSoal] = useState(0);
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 groupName = `soal[${currentQuestion.id}]`; // ✅ 唯一、语义化 name
return (
<div classname="quiz-container">
<h2 classname="text-lg font-semibold mb-4">第 {currentSoal + 1} 题:{currentQuestion.text}</h2>
<div classname="space-y-3">
{currentQuestion.opsi.map((option, idx) => (
<label key="{option.id}" classname="flex items-center cursor-pointer">
<input type="radio" name="{groupName}" value="{option.id}" checked option.id onchange="{handleOptionChange}" classname="mr-3 h-4 w-4 text-blue-600 focus:ring-blue-500"><span>{option.opsi}</span>
</label>
))}
</div>
<div classname="mt-6 flex justify-between">
<button onclick="{()"> setCurrentSoal(Math.max(0, currentSoal - 1))}
disabled={currentSoal === 0}
className="px-4 py-2 bg-gray-200 rounded disabled:opacity-50"
>
上一题
</button>
<button onclick="{handleNextQuestion}" disabled>= questions.length - 1}
className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
>
{currentSoal === questions.length - 1 ? '提交' : '下一题'}
</button>
</div>
</div>
);
};
export default QuizComponent;
? 关键注意事项:
-
name必须全局唯一 per question:使用soal[${id}]格式,既兼容后端接收习惯(如 Laravel 的soal.123),又天然避免 name 冲突; -
checked必须显式比较:selectedOptions[name] === option.id,不可省略===或误写为==/in/includes; -
使用函数式更新
setSelectedOptions:避免闭包中读取过期 state(示例中已优化为prev => ({...prev, [name]: value})); -
初始 state 无需预设所有题目:
selectedOptions是稀疏对象,只存用户实际选择的项,轻量且高效。
? 进阶建议:若需支持「回到前题修改答案」并保留历史选择,当前设计已天然支持——因为 selectedOptions 持久化存储所有题目的答案,切换 currentSoal 不会清空数据。如需「每题仅允许一次作答」,可在 handleOptionChange 中增加防重复逻辑,但非本问题范畴。
通过以上修正,即可彻底解决「选了第一题 A 选项,第二题第一个选项也自动选中」的同步污染问题,实现专业、健壮的多题单选交互体验。










