Reactjs映射方法选择唯一id



在我的react应用程序中,我有一个这样的映射方法:

data.qandASections.map((item, i) => {
return (
<div className="qaElement" key={i} onClick={showAnswer(i)}>
<div className="question">
<span>{item.question}</span>
<span className="arrowDown" id={"arrow"+i}></span>
</div>
<div className="answer" id={"answer"+i} style={{display: "none"}}>{item.answer}</div>
</div>
)
})

我想在函数showAnswer中访问我创建的唯一ID(answer0,answer1…answern(

功能看起来像这个

function showAnswer(i){
const answerId = "answer" + i
const arrowId = "arrow" + i
const answer = document.getElementById(answerId)
const arrow = document.getElementById(arrowId)
if (answer.style.display = "none") {
answer.style.display = "block"
arrow.style.transform = "rotate(45deg)"
} else {
answer.style.display = "none"
arrow.style.transform = "rotate(-135deg)"
}
}

遗憾的是,这并没有像我所说的那样奏效;未处理的拒绝(TypeError(:无法读取null的属性"style";对于我在映射函数中创建的id元素("答案"+i(和("箭头"+i有没有其他方法可以访问这些元素?

只需更改此字符串:

<div className="qaElement" key={i} onClick={showAnswer(i)}>

到此:

<div className="qaElement" key={i} onClick={() => showAnswer(i)}>

最新更新