【发布时间】: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])}/>
{Object.values(x)[0]}
{
}
</label>
</div>
</div> }
) : <span>Empty</span>
}
</div>
</div>;
})
【问题讨论】:
-
我猜你想将
checked属性添加到你的输入组件中。可能类似于checked={answers[index].userChoice.option === Object.keys(x)}。 -
@Chris 我怎样才能在那里获得索引。
-
哦,我明白了。需要先在数组中找到正确答案吗?
-
没错,由于数组是动态的,它有可能没有任何价值。在这种情况下,它将保持未选中状态,如果“选项”不匹配,则相同。