首页 > 解决方案 > 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>

任何想法?

标签: javascriptreactjs

解决方案


buttonSelected您可以使用 bool ( )数组初始化状态变量。然后,handleClickindex您截取单击的按钮并切换布尔值。在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>

推荐阅读