如何对多个元素使用 useState React Hook?

how to use useState react hook for more than one element?

我第一次使用 react hooks 使用 mern(mongo 表达 reactjs 和 nodejs)构建一个全栈网站。 所以我有 bootstrap 带有 collapse 按钮的卡片来隐藏卡片正文,但我有 6 张卡片,并且 collapse 按钮与 useState 挂钩一起使用,在某种程度上onClick 将 expand 属性 设置为 false,反之亦然。 我的问题是我应该为 6 张卡使用 6 个 useState 挂钩吗?或者以任何方式,有一些解决方案。 ps。如果在所有卡片上使用相同的挂钩,则 onClick 将展开所有卡片。

这是我的一个 useState 和一张卡片的代码:

const [open1, setOpen1] = useState(false);
 <Button

        onClick={() => setOpen1(!open1)}
        aria-controls="example-collapse-text"
        aria-expanded={open1}
      >
        click
      </Button>
      <Collapse in={open1}>
        <div id="example-collapse-text">
        This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.
        </div>
      </Collapse>

你能试试下面的逻辑吗?

const [open, setOpen] = useState(1);
<Button
onClick={() => setOpen(1)}
aria-controls="example-collapse-text"
aria-expanded={(open === 1)? true : false}>
click
</Button>
<Collapse in={(open === 1)? true : false}>
<div id="example-collapse-text">
This is a longer card with supporting text below as a natural
    lead-in to additional content. This content is a little bit longer.
</div>
</Collapse>

<Button
  onClick={() => setOpen(2)}
  aria-controls="example-collapse-text"
  aria-expanded={(open === 2)? true : false}>
  click
</Button>
<Collapse in={(open === 2)? true : false}>
  <div id="example-collapse-text">
  This is a longer card with supporting text below as a natural
      lead-in to additional content. This content is a little bit longer.
  </div>
</Collapse>

好吧,通过为卡片制作一个组件然后将其用作 jsx 元素解决了这个问题。

export default function DepartmentCard() {
const [open, setOpen] = useState(false);

<Button
onClick={() => setOpen(open)}
aria-controls="example-collapse-text"
aria-expanded={(open === 1)? true : false}>
click
</Button>
<Collapse in={open}>
<div id="example-collapse-text">
This is a longer card with supporting text below as a natural
    lead-in to additional content. This content is a little bit longer.
</div>
</Collapse>
}

顺便说一句,它是相同的代码,但我没有使用它 6 次,而是作为一个组件制作,并使用组件标签 6 次。 但不同之处在于现在每个组件都有自己的状态

示例:

ReactDOM.render(
<div>
<DepartmentCard/>
<DepartmentCard/>
<DepartmentCard/>
<DepartmentCard/>
<DepartmentCard/>
<DepartmentCard/>
</div>

或者您可以简单地使用 map() 函数或循环来渲染 6 张卡片。 并且你可以使用道具来改变每张卡片的主体。

您需要做的是,创建一个名为component 的文件夹(名称不一定相同,但很多人都遵循)。在该文件夹中制作这样的卡片组件

import React, { useState } from "react";

const card = ({ prop1, prop2 }) => {
  const [isOpen, setOpen] = useState(false);

  const collapseListener = () => {
    setOpen((prvState) => !prvState);
  };

  return (
    <div>
      <button onClick={collapseListener}>{/* button to collapse */}</button>
      <collable collapse={isOpen}>
        {/* your collapasble component */}
        <h1>{prop1}</h1>
        <h1>{prop2}</h1>
      </collable>
    </div>
  );
};

export default card;

然后你可以从任何地方导入这个卡片组件,然后像这样使用它

<Card prop1={'first'} prop2={'second'}  />