Javascript 使用react钩子将类添加到单个按钮
我试图将css类添加到活动按钮中,但使用下面的代码,它将添加到所有按钮中。 所以现在我有两个按钮,点击后,它为两个按钮添加了代码,而不是一个被点击的按钮 我错过了什么Javascript 使用react钩子将类添加到单个按钮,javascript,reactjs,Javascript,Reactjs,我试图将css类添加到活动按钮中,但使用下面的代码,它将添加到所有按钮中。 所以现在我有两个按钮,点击后,它为两个按钮添加了代码,而不是一个被点击的按钮 我错过了什么 import React, { useState } from 'react' export default function ProductPage() { const [size, setSize] = useState('') const [color, setColor] = useState('') co
import React, { useState } from 'react'
export default function ProductPage() {
const [size, setSize] = useState('')
const [color, setColor] = useState('')
const [isActive, setActive] = useState(false)
const toggleClass = () => {
setActive(!isActive)
}
return (
<>
<div className="grid grid-cols-2 gap-10 p-14">
{productSizes.map((size,index) => {
return (
<button className={`hover:bg-black hover:text-white cursor-pointer ${isActive ? 'bg-black text-white' : null}`} role="button" tabIndex={0}
onClick={() => {toggleClass(); setSize(size)}}
onKeyDown={() => setSize(size)} key={index}>{size}</button>
)
}
)}
</div>
<div className="colors mb-8">
<p className="tracking-wider mb-2">Color</p>
{productColors.map(color => {
return (
<span className="p-2 border-gray-200 border mr-2 hover:bg-black hover:text-white cursor-pointer" role="button" tabIndex={0} onClick={() => setColor(color)} onKeyDown={() => setSize(size)} key={color.id}>
{color}
</span>
)
}
)}
</div>
<button className="btn bg-green-500 mt-4 snipcart-add-item p-4 rounded text-white">
Add to cart
</button>
</>
)
}
import React,{useState}来自“React”
导出默认函数ProductPage(){
常量[大小,设置大小]=使用状态(“”)
const[color,setColor]=useState(“”)
常量[isActive,setActive]=useState(false)
常量切换类=()=>{
setActive(!isActive)
}
返回(
{productSizes.map((大小,索引)=>{
返回(
{toggleClass();设置大小(大小)}
onKeyDown={()=>setSize(size)}key={index}>{size}
)
}
)}
颜色
{productColors.map(颜色=>{
返回(
setColor(color)}onKeyDown={()=>setSize(size)}key={color.id}>
{color}
)
}
)}
添加到购物车
)
}
问题
您使用单个布尔值isActive
来标记按钮是否处于活动状态,因此所有按钮同时处于活动/非活动状态
解决方案
存储可与特定按钮关联的isActive
状态值。我建议使用索引
function ProductPage() {
...
const [isActive, setActive] = useState(null); // <-- initial null state
const toggleClass = (index) => {
// toggle active/inactive index
setActive((isActive) => (isActive === index ? null : index));
};
return (
<>
<div className="grid grid-cols-2 gap-10 p-14">
{productSizes.map((size, index) => {
return (
<button
className={`hover:bg-black hover:text-white cursor-pointer ${
isActive === index ? "bg-black text-white" : null // <-- check index match
}`}
onClick={() => {
toggleClass(index); // <-- pass index to toggle handler
setSize(size);
}}
onKeyDown={() => setSize(size)}
key={index}
>
{size}
</button>
);
})}
</div>
...
</>
);
}
函数ProductPage(){
...
常量[isActive,setActive]=useState(null);//{
//切换活动/非活动索引
setActive((isActive)=>(isActive==index?null:index));
};
返回(
{productSizes.map((大小,索引)=>{
返回(
{size}
);
})}
...
);
}
感谢Drew抽出时间帮助我。按照你的建议,它工作得很好。