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

React JS中如何根据已有答案实现动态Checkbox自动勾选

动态表单自动勾选Checkbox实现方案

核心调整点

  • 给input标签新增checked属性,绑定匹配逻辑:每次渲染时查找answers数组中对应questionId的答案,判断userChoice.option是否等于当前选项的key,匹配则返回true实现自动勾选
  • 修正状态更新逻辑:修改answers前先做数组浅拷贝,避免直接修改原状态引用导致React无法触发重渲染
  • 修复原代码中无效的非法ID判定逻辑:原answers.length > Fields写法错误,调整为判定questionId是否在合法字段范围内

示例图片

修改后的完整代码如下:

import { useState, useEffect } from "react";
import fieldsL from "./fields.json"; 

function App() { 
  const [Fields, setFields] = useState([]);
  const [answers, setAnswers] = useState([]);

  const updateAnswer = (qid, option, optionValue) => {
    // 先浅拷贝数组,不直接修改原状态
    let ans = [...answers];
    let singleAns = {
      questionId: qid,
      userChoice: { 
        option: option, 
        optionValue: optionValue, 
        isChecked: true
      }
    };
    // 修正非法ID判定逻辑,可根据实际业务调整判定规则
    const validQids = Fields.question?.map(item => item.questionId) || [];
    if(!validQids.includes(qid)) return console.warn("Invalid Question ID");

    const existIndex = ans.findIndex(sp => sp.questionId === qid);
    if(existIndex > -1) {
      ans[existIndex].userChoice.option = option;
      ans[existIndex].userChoice.optionValue = optionValue;
      console.log("Existing Answer Updated");
    } else {
      ans.push(singleAns);
    }
    ans.sort((a, b) => parseFloat(a.questionId) - parseFloat(b.questionId)); 
    setAnswers(ans);
    console.log(ans);
  }

  useEffect(()=>{
    console.log("useEffect");
    setFields(fieldsL.data);
  }, [])

  const Questions = fieldsL.data?.question || [];
  const displayFields = Questions.map((e, index) => {
    return <div key={index} >
      <label className="label">{e.content}</label>
      <div className="control">
        {
          e.radio ? e.option.map((x, index2) => {
            const currentOption = Object.keys(x)[0];
            // 匹配当前选项是否要勾选
            const isChecked = answers.some(ans => 
              ans.questionId === e.questionId && ans.userChoice.option === currentOption
            );
            return <div classID="field" key={index2}>
              <div classID="control">
                <label classID="checkbox">
                  <label> {currentOption} </label>
                  <input 
                    type="checkbox" 
                    name="question" 
                    checked={isChecked}
                    onChange={()=> updateAnswer(e.questionId, currentOption, Object.values(x)[0])}
                  />
                  &nbsp; {Object.values(x)[0]}
                </label>
              </div>
            </div> 
          }) : <span>Empty</span>
        }
      </div>
    </div>;
  })

  return <div>{displayFields}</div>
}

export default App;

内容的提问来源于stack exchange,提问作者Faqahat Fareed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:27:03