active class in react js



抱歉。我有一个按钮,然后我添加一个活动类,当我点击它,但当我点击它所有的按钮变得活跃,我如何修复它?这是代码

<div className="">
{category.items.length === 0 ? (
<div>There is no property at this categories</div>
) : (
category.items.map((item, index2) => {
return (
<div key={`category-${index1}-item-${index2}`}>
{buttons.map((buttonLabel, i) => (
<button
key={i}
name={buttonLabel}
onClick={(event) => handleClick(event, i)}
className={
i === clickedId
? 'py-4 pl-3 customButton active '
: 'customButton py-4 pl-3'
}
>
{item.name}
</button>
))}
</div>
);
})
)}
</div>

这是当按钮被调用

时的代码

<ButtonCategory
data={category.categories}
buttons={[category.categories]}
doSomethingAfterClick={printButtonLabel}
/>

您将为每个项目返回相同的按钮集。有更好的方法可以做到这一点,但在您当前的设置下,这应该可以工作:

buttons.map((buttonLabel, i) => {
const key = `${index2}.${i}`
return (
<button
key={key}
name={buttonLabel}
onClick={(event) => handleClick(event, key)}
className={
key === clickedId
? "py-4 pl-3 customButton active "
: "customButton py-4 pl-3"
}
>
{item.name}
</button>
)});

不要忘记初始化你的clickdid状态为null或undefined而不是number

你应该在handleClick函数中设置被点击按钮的索引为clickdid。所以你的handleClick函数必须像这样

const handleClick = (event, i) => {
setClickedId(i)
// other logic
}

最新更新