You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React动态问卷中RadioButton选择异常问题排查与修复

修复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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 19:54:59