如何不一次打开所有下拉菜单?

How to not open all dropdowns at once?

我知道标题看起来很简单也很简单,但请帮助我,所以基本上当我尝试打开一个菜单时,它会打开所有菜单

import React from "react";

export default function App() {
  const [active, setActive] = React.useState(false);
  function handleClick() {
    setActive(!active);
  }

  const text = [
    {
      id: 1,
      name: "Hello",
      subText: [
        {
          id: 1,
          name: "Sub Hello"
        }
      ]
    },
    {
      id: 2,
      name: "Bye",
      subText: [
        {
          id: 2,
          name: "Sub Bye"
        }
      ]
    }
  ];
  return (
    <div style={{ backgroundColor: "gray", padding: 4 }}>
      {text?.map(({ name, id, subText }) => (
        <div style={{ display: "flex", alignItems: "center" }}>
          <ul style={{ width: 100 }}>
            <li style={{ cursor: "pointer" }} onClick={handleClick}>
              {name}
            </li>
          </ul>
          <div>
            {active &&
              subText?.map(({ name, id }) => (
                <ul key={id}>
                  <li>{name}</li>
                </ul>
              ))}
          </div>
        </div>
      ))}
    </div>
  );
}

这是实时代码: https://codesandbox.io/s/angry-moser-dh4mit?file=/src/App.js:0-1051

传递父菜单 ID 以检查应打开哪个子菜单会有所帮助。 在下面附上更改后的代码。 只是传递了 id 并保持在点击时的状态。否则状态将是未定义的。

export default function App() {
  const [active, setActive] = React.useState(undefined);
  function handleClick(id) {
    setActive(id === active ? undefined :id);
  }

  const text = [
    {
      id: 1,
      name: "Hello",
      subText: [
        {
          id: 1,
          name: "Sub Hello"
        }
      ]
    },
    {
      id: 2,
      name: "Bye",
      subText: [
        {
          id: 2,
          name: "Sub Bye"
        }
      ]
    }
  ];
  return (
    <div style={{ backgroundColor: "gray", padding: 4 }}>
      {text?.map(({ name, id, subText }) => (
        <div style={{ display: "flex", alignItems: "center" }}>
          <ul style={{ width: 100 }}>
            <li style={{ cursor: "pointer" }} onClick={() => handleClick(id)}>
              {name}
            </li>
          </ul>
          <div>
            {active === id &&
              subText?.map(({ name, id }) => (
                <ul key={id}>
                  <li>{name}</li>
                </ul>
              ))}
          </div>
        </div>
      ))}
    </div>
  );
}