我有一个React组件,它接受一个数组,并使用map()
呈现组件。问题是index
的{{1}}值似乎恢复为0,无论与map()
侦听器关联的匿名函数是什么。
onChange
function Questions({ questions, answers, toggleAnswers }) {
const questionButtons = questions.map((question, index) => {
if (answers[index - 1] === undefined || answers[index - 1] === 'true') {
const buttonIndex = index;
console.log('BEFORE RETURN etv:', event.target.value, 'index:', index, 'buttonIndex:', buttonIndex);
return (
<CustomFormComponent
key={ index }
name={ question.substr(0,5) }
label={ question }
value={ answers[index] }
handleChange={ (event) => {
console.log('ISTHISEVER NOT ZERO?', buttonIndex);
toggleAnswers(event, index);
}
}
/>
);
} else {
return null;
}
});
return (
<div>
{ questionButtons }
</div>
);
}
然后点击“是”按钮后:
BEFORE RETURN etv: undefined index: 0 buttonIndex: 0
如果我点击任何一个“否”按钮,ISTHISEVER NOT ZERO? 0
BEFORE RETURN etv: true index: 0 buttonIndex: 0
BEFORE RETURN etv: true index: 1 buttonIndex: 1
ISTHISEVER NOT ZERO? 0
BEFORE RETURN etv: true index: 0 buttonIndex: 0
BEFORE RETURN etv: true index: 1 buttonIndex: 1
仍然等于0。