【问题标题】:How to check Dynamic Checkbox in React JS如何在 React JS 中检查动态复选框
【发布时间】:2021-11-17 13:18:38
【问题描述】:

我有一个具有以下实现的动态表单。问题是如果该“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>;
})

【问题讨论】:

  • 我猜你想将 checked 属性添加到你的输入组件中。可能类似于checked={answers[index].userChoice.option === Object.keys(x)}
  • @Chris 我怎样才能在那里获得索引。
  • 哦,我明白了。需要先在数组中找到正确答案吗?
  • 没错,由于数组是动态的,它有可能没有任何价值。在这种情况下,它将保持未选中状态,如果“选项”不匹配,则相同。

标签: reactjs forms checkbox


【解决方案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) 复杂度,因为您将在循环中执行循环。但是,对于较小的阵列,这根本不是问题。

【讨论】:

  • 我之前和现在都试过了,每次迭代的索引都返回-1。 prnt.sc/1tfxnvg
  • @FaqahatFareed 也许我误解了您的数据是如何建模的。如果x 的键是为了匹配userChoice.option,那么这应该可以工作。
  • 正确的键是 Object.keys(x)[0] 但是它似乎也不起作用,你能建议一个更好的实现吗?
  • 你能用answers(整个结构)和Object.keys(x)的console.log输出更新你的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-26
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多