多个元素的动态反应切换按钮

Dynamic react toggle button for multiple elements

我需要在 true/false 的反应状态下切换多个方块,但 true 和 false 同时适用于所有方块。

import { useState } from "react";
...
const [toggleThisElement, setToggleThisElement] = useState(false);
...

{
    data.map((d, id) => {
        return (
            <div className="single-history" key={id}>
                <div className="h-head">
                    click this div for toggle h-info block
                </div>

                <div className="h-info">toggling block</div>
            </div>
        )
    })
}

目前,您所有的切换项都处于同一状态。为避免这种情况,请创建一个单独的组件来切换逻辑,称为 ToggleItem,如下所示。

import { useState } from "react";

const ToggleItem = ({ discription, id }) => {
  const [toggleThisElement, setToggleThisElement] = useState(false);
  return (
    <div className="single-history" key={id}>
      <button
        className="h-head"
        onClick={() => setToggleThisElement((prev) => !prev)}
      >
        click this btn for toggle h-info block {id}
      </button>

      {toggleThisElement && <div className="h-info">{discription}</div>}
    </div>
  );
};

export default function App() {
  const data = ["first", "second", "third"];

  return (
    <>
      {data.map((d, id) => {
        return <ToggleItem id={id} discription={d} />;
      })}
    </>
  );
}