我有一个多页表单,它为每个可能的答案呈现按钮列表。
我目前正在使用 getElementByID 在单击按钮时更改按钮样式。我认为这不是反应的好习惯。
如果按钮与地图一起动态显示,我可以使用 useRef 挂钩来定位 DOM 元素并更改其样式而不是使用 getElementByID 吗?
{answers.map((answer, count = 0) => {
return (
<Button
key={count}
id=`button${count}`
onClick={(e) => {
document.getElementById(`${e.currentTarget.id}`).style.color = "white";
}}
>
<ButtonTitle>{answer.name}</ButtonTitle>
</Button>
);
})}
(safari 上的动画破坏了 active 样式,所以我不能使用 active 伪元素)
您可以通过添加新状态并按active
该状态切换类来做到这一点。编写类似这样的代码。
const [activeindex, setActiveIndex] = useState("");
return(
<>
{answers.map((answer, count = 0) => {
return (
<Button
key={count}
className={count==activeindex?"acvie":""}
onClick={(e) => {
setActiveIndex(count)
}}
>
<ButtonTitle>{answer.name}</ButtonTitle>
</Button>
);
})}
}
</>
并在 css 文件中使用 .active 类。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句