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

React实现问卷仅单个问题可启用Toggle Switch功能求助

实现单选Toggle Switch的动态问卷问题

需求:

  • 问卷支持点击“Add”按钮动态添加问题条目
  • 每个问题附带Toggle Switch,用于标记为条件判定问题
  • 单选规则:启用某一问题的开关时,其余所有问题的开关自动关闭

原代码问题分析

原handleInputChange函数中处理switch的逻辑存在错误:

  • 错误使用event.target.value修改其他项状态,switch组件的选中状态应通过checked属性获取,而非value
  • 取反逻辑不符合单选需求,正确逻辑应为仅当前选中项设为true,其余全为false

修正后的完整代码方案

1. 修正输入变更处理函数

const templateRow = { question: '', questionType: '', questionState: '', decidingQuestion: false };
const [inputFields, setInputFields] = useState([templateRow]);

const handleInputChange = (index, event) => {
  const values = [...inputFields];
  const { name, checked, value } = event.target;

  if (name !== "decidingQuestion") {
    // 处理普通输入项的内容变更
    values[index][name] = value;
  } else {
    // 处理Toggle Switch的单选逻辑
    if (checked) {
      // 选中当前项时,将所有其他项的判定开关设为关闭
      values.forEach((item, idx) => {
        item.decidingQuestion = idx === index;
      });
    } else {
      // 取消选中当前项时,仅关闭当前项的开关
      values[index].decidingQuestion = false;
    }
  }

  setInputFields(values);
};

2. 修正Switch组件的渲染

确保每个动态生成的Switch拥有唯一ID,避免DOM冲突:

{inputFields.map((input, index) => (
  <div key={index} className="question-item">
    {/* 其他问题输入组件(如question、questionType等) */}
    <Form.Check
      type="switch"
      id={`decidingQuestion-${index}`} // 动态生成唯一ID
      name="decidingQuestion"
      checked={input.decidingQuestion}
      onChange={(event) => handleInputChange(index, event)}
      label="设为条件判定问题" // 可选:添加标签提升可用性
    />
  </div>
))}

3. 动态添加问题的函数(参考)

const addInputField = () => {
  setInputFields(prev => [...prev, templateRow]);
};

// 对应Add按钮
<button onClick={addInputField}>Add Question</button>

功能验证

  • 点击任意问题的Toggle Switch,该问题会被标记为判定问题,其余所有问题的开关自动关闭
  • 取消当前选中的开关,仅该问题的开关关闭,其他问题状态保持不变(若需强制必须选中一个,可移除else分支,禁止取消操作)

内容的提问来源于stack exchange,提问作者Abcd Efgh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:15:34