用索引改变单个元素的颜色

react change color of a single element with index

我两天前才开始学习反应,我想改变点击按钮的颜色。我有 2 个按钮,单击时每个按钮都应该改变颜色,但是,当我只单击一个按钮时,我的代码会更改两个按钮的颜色。我读到我需要在某处使用索引,但我不确定在哪里或如何映射索引。任何帮助都感激不尽。这是我的代码:

let ash = "#959595";
let purple = "#8c52ff";

const [buttonColor, setButtonColor] = useState(ash);

function handleColorChange(e) {
    const button = e.target.style.backgroundColor;
    const newButton = e.target.style.backgroundColor;

    const newColor = buttonColor === ash ? purple : ash;
    setButtonColor(newColor);
}

return (
    <div>
        <button
            className="days-btn"
            style={{ backgroundColor: buttonColor }}
            color={buttonColor}
            onClick={handleColorChange}
        >
            M
        </button>
        &nbsp;
        <button
            className="days-btn"
            style={{ backgroundColor: buttonColor }}
            color={buttonColor}
            onClick={handleColorChange}
        >
            T
        </button>
    </div>
);

问题是两个按钮共享相同的状态。您可以将 color-changing 逻辑保留在单独的 Button 组件中。所以 Buttons 可以独立改变它们的颜色。

import { useState } from "react";

let ash = "#959595";
let purple = "#8c52ff";

const Button = ({ buttonText }) => {
  const [buttonColor, setButtonColor] = useState(ash);

  function handleColorChange(e) {
    const newColor = buttonColor === ash ? purple : ash;
    setButtonColor(newColor);
  }

  return (
    <button
      className="days-btn"
      style={{ backgroundColor: buttonColor }}
      color={buttonColor}
      onClick={handleColorChange}
    >
      {buttonText}
    </button>
  );
};

export default Button;

在您的其他组件中创建两个按钮,根据需要提供任何道具。

import Button from "./Button";

const App = () => {
  return (
    <div>
      <Button buttonText="M" />
      <Button buttonText="T" />
    </div>
  );
};

export default App;

Code Sandbox