javascript - 如何处理点击循环中的特定按钮?
问题描述
我创建了以下设计:
这是反应js代码:
{this.props.BetSlipDataObj.betDetails.data.map(
(value, index) => {
<div className="d-flex justify-content-end">
<button
className="info-button"
data-toggle="collapse"
href="#collapseExample"
role="button"
aria-expanded="false"
aria-controls="collapseExample"
// onClick={
// value.betId != null
// ? _this.getBetIdDetails(value.betId)
// : value.childId != null
// ? _this.getBetIdDetails(value.childId)
// : ""
// }
>
</div>
})}
在这里,我正在尝试执行以下任务如果我单击一个按钮,它应该展开框但是如果我单击一个按钮,所有框都在展开。如果我在单击时调用某个方法,它会被无限调用
有人可以帮我更正代码吗?
解决方案
您可以在单击按钮时调用函数。我认为它是无限调用的,因为您没有传递对该函数的引用。
{this.props.BetSlipDataObj.betDetails.data.map(
(value, index) => (
<div className="d-flex justify-content-end" key={index}>
<button
className="info-button"
data-toggle="collapse"
href="#collapseExample"
role="button"
aria-expanded="false"
aria-controls="collapseExample"
onClick={
value.betId != null
? () => _this.getBetIdDetails(value.betId)
: value.childId != null
? () => _this.getBetIdDetails(value.childId)
: () => {}
}
>
</div>
)
)}
你也错过了key
div 上的道具
编辑:一个按钮打开所有框,因为它们都具有相同的 ID 和控件。要使 ID 和控件唯一,您可以执行以下操作:
{this.props.BetSlipDataObj.betDetails.data.map(
(value, index) => (
<div className="d-flex justify-content-end" key={index}>
<button
className="info-button"
data-toggle={`collapse${index}`}
href={`#collapseExample${index}`}
role="button"
aria-expanded="false"
aria-controls={`collapseExample${index}`}
onClick={
value.betId != null
? () => _this.getBetIdDetails(value.betId)
: value.childId != null
? () => _this.getBetIdDetails(value.childId)
: () => {}
}
>
</div>
)
)}