开发者问题收集

如何在 React JS 中检查动态复选框

2021-09-24
1283

我有一个动态表单,其实现如下。问题是,如果该“questionID”的答案在具有所选选项(即 A、B)的答案数组中存在,我想“选中”复选框。因此检查的条件应该是 answers[index].userChoice.option 等于 Object.keys(x)。 在此处输入图片描述

import fieldsL from "./fields.json"; 

function App() { 
  let [Fields , setFields] = useState([]);
  let [answers, setAnswers] = useState([]);
const updateAnswer = ((qid,option,optionValue) => {
      let ans = answers;
      let singleAns = {
        questionId : qid,
        userChoice: 
        { 
          option: option, 
          optionValue: optionValue, 
          isChecked: true
        }
      };
      if(answers.length > Fields) return console.warn("Invalid Question ID")
      if(answers.find((sp) => sp.questionId === qid)) {
        var index = answers.map(function(x1) {return x1.questionId}).indexOf(qid);
        answers[index].userChoice.option = option;
        answers[index].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(answers)
  })

useEffect(()=>{
  console.log("useEffect")
  setFields(fieldsL.data)
},[])
let Questions = fieldsL.data.question;
let 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) => {

  console.log(index)
  //console.log(x)
 return <div classID="field" key={index2}>
<div classID="control">
  <label classID="checkbox">
    <label> {Object.keys(x)[0]}     </label>

    <input type="checkbox" name="question" onChange={()=> updateAnswer(e.questionId,Object.keys(x)[0],Object.values(x)[0])}/>
    &nbsp; {Object.values(x)[0]}
    { 

    }
  </label>
</div>
</div> }
) : <span>Empty</span>
}
</div>
</div>;
})

1个回答

在循环的每次迭代中,您可以执行以下操作:

const value = Object.keys(x);
const answerIndex = answers.findIndex(a => a.userChoice.option === value);

然后在返回中:

<input
  type="checkbox"
  name="question"
  checked={answerIndex >= 0}
  onChange={()=> updateAnswer(e.questionId,Object.keys(x)[0],Object.values(x)[0])}
/>

显然,如果您的数据结构不同,情况会更好,因为上面的代码会给您带来 O(2n) 复杂度,因为您会在循环内执行循环。但是,对于较小的数组,这根本不是问题。

Chris
2021-09-24