javascript - onclick反应,我想让我的按钮改变颜色
问题描述
使用地图功能并显示它的按钮不止一个。想要更改我单击的按钮的背景颜色。而其他人则希望它保持原样。当我再次单击另一个按钮时,仅更改该按钮的 BG 颜色。这就是我已经拥有的:
const handleClick = (option, index) => {
const nextQuestion = currentQuestion + 1;
if (data[currentQuestion].answer === option) {
// setChangeColor(isCorrect);
isCorrect = "bg-success text-white";
setTimeout(() => {
setCurrentQuestion(nextQuestion);
setMoneyLadder(moneyLadder - 1);
setChangeColor("");
}, 2000);
} else {
// setChangeColor(isIncorrect);
isIncorrect = "bg-danger";
setTimeout(() => {
window.location.reload();
setCurrentQuestion(0);
setMoneyLadder(15);
setChangeColor("");
}, 2000);
}
};
<div className="answers">
{data[currentQuestion].options.map(
(option, index) => (
<button
className={
// data[currentQuestion].answer ===
// option
// ? "text-success"
// : ""
}
key={index}
onClick={() =>
handleClick(option, index)
}
dangerouslySetInnerHTML={{
__html: `${index + 1}) ${option}`,
}}
></button>
)
)}
</div>
任何想法?
解决方案
buttonSelected
您可以使用 bool ( )数组初始化状态变量。然后,handleClick
与index
您截取单击的按钮并切换布尔值。在button
's 风格中,您可以编写:
{{backgroundColor: buttonSelected[index] ? 'red':'green'}}
red
因此,如果单击按钮,则backgroundColor 变为,green
否则:
const [buttonSelected, setButtonSelected] = useState(new Array(data[currentQuestion].options.length).fill(false));
const handleClick = (index) => {
let result = [...buttonSelected];
result[index] = !result[index];
setButtonSelected(result);
}
<div className="answers">
{data[currentQuestion].options.map(
(option, index) => (
<button
className={
// data[currentQuestion].answer ===
// option
// ? "text-success"
// : ""
}
style={{backgroundColor: buttonSelected[index] ? 'red':'green'}}
key={index}
onClick={() =>
handleClick(index)
}
dangerouslySetInnerHTML={{
__html: `${index + 1}) ${option}`,
}}
></button>
)
)}
</div>
推荐阅读
- javascript - 控制器到控制器 - 处理单击以显示/隐藏 div
- python - 在多索引列上执行聚合
- c# - 收听所有短信并在 Xamarin Android 中收到明确消息时执行某些操作
- android - 如何防止安卓设备从 USB 共享屏幕?
- python - 如何在 PyQt5 的特定区域内的鼠标单击事件上绘制椭圆?
- arrays - 使用 req.body 使用 Mongoose 更新嵌入式数组文档
- github-pages-deploy-action - Gh-pages 没有显示正确的东西
- python - 查询 django 数据库时出错:ValueError:注释“代码”与模型上的字段冲突
- outlook - 如何在 Outlook 插件中获取附件?
- python - 如何在python中获取比较时间值和差异