React JS- 多个按钮

React JS- Multiple Buttons


我正在尝试制作 多个切换 按钮,每当用户点击其中任何一个按钮时,我都希望它变得更暗一些。因此,该用户知道他们点击了哪一个。


这是我编写的示例代码。 代码:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [active, setActive] = useState("first");

  return (
    <>
    <div className="App"> 
    <button className="button" active={active === "first"} onClick={() => {setActive("first"); }} >first</button>
    <button className="button" active={active === "Second"} onClick={() => {setActive("Second"); }} >Second</button>
    <button className="button" active={active === "Third"} onClick={() => {setActive("Third"); }} >Third</button>
      </div>
    </>
  );
}

现在,如何创建一个 OnClick 函数来保存 点击后? 功能?

你可以这样做:

<button
  className={`button ${active === "first" ? "activeButton" : ""}`}
  onClick={() => {
    setActive("first");
  }}
>
  first
</button>
<button
  className={`button ${active === "Second" ? "activeButton" : ""}`}
  onClick={() => {
    setActive("Second");
  }}
>
  Second
</button>
<button
  className={`button ${active === "Third" ? "activeButton" : ""}`}
  onClick={() => {
    setActive("Third");
  }}
>
  Third
</button>

然后在你的 css 文件中:

.activeButton {
  background-color: red;
}