reactjs - 在 Modal React Bootstrap 中将一张卡链接到另一张卡

标签 reactjs react-bootstrap

我正在尝试实现这个:

位于模态框内的 Accordion 内的卡片,该卡片有一个按钮,单击该按钮时应转到下一张卡片。

我最多可以有 10 个这样的东西,那么在这种情况下我该如何让它发挥作用呢?更重要的是,我试图添加某种链接功能,例如如何将页面与react-router-dom链接,但在react-bootstrap的模态中。

<强> Link to CodeSandbox

这是位于模态中的 Accordion ,卡片中带有 Age 按钮。

enter image description here

当您点击上一张图片中的Age时,它应该会打开类似下一张图片的内容,该图片也必须位于相同的Modal中:

enter image description here

这是 Accordion 的示例,它位于 Modal 中:

const AccordionModal = () => {
  return (
    <Accordion>
      <Card>
        <Card.Header>
          <Accordion.Toggle as={Button} variant="light" eventKey="0">
            Basic Preprocessing Variables
          </Accordion.Toggle>
        </Card.Header>
        <Accordion.Collapse eventKey="0">
          <Card.Body>
            <Button variant="primary">Age</Button>
          </Card.Body>
        </Accordion.Collapse>
      </Card>
      <Card>
   </Accordion>
  )
}

最佳答案

在事件中返回组件不会呈现该组件。

这里有两种方法,您可以在 this sandbox 中找到。 .

在组件级别,您可以切换一个 bool 值,有条件地显示 <Sample />不过组件。

参见conditional renderinguseState .

import { useState } from "react";
import { Button, Card } from "react-bootstrap";

const ExpandableCard = ({ label, children, ...rest }) => {
  const [expanded, setExpanded] = useState(false);

  return (
    <Card.Body {...rest}>
      <Button variant="primary" onClick={() => setExpanded(true)}>
        {label}
      </Button>
      {expanded && children}
    </Card.Body>
  );
};

如果您不想在组件级别执行此操作,则可以将可见索引数组保留在状态中。

import { useState } from "react";
import { Button, Card } from "react-bootstrap";

const cards = [
  {
    label: 'Card1',
    content: () => <p>Card1 (Content)</p>
  },
  {
    label: 'Card2',
    content: () => <p>Card2 (Content)</p>
  }
]

const ExpandableCardList = () => {
  const [expandedSections, setExpandedSections] = useState([]);

  const handleClick = (index) => {
    if (expandedSections.includes(index)) return;
    setExpandedSections((prevSections) => [...prevSections, index]);
  };
  
  return cards.map(({ label, content: ExpandedContent }, index) => (
    <Card.Body key={index}>
      <Button variant="primary" onClick={() => handleClick(index)}>
        {label}
      </Button>
      {expandedSections.includes(index) && <ExpandedContent />}
    </Card.Body>
  ));
};

关于reactjs - 在 Modal React Bootstrap 中将一张卡链接到另一张卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66549477/

相关文章:

reactjs - 使用 api 中的 id 获取数据,但在地址栏显示替代文本,例如Next.js 中的内容标题

css - 如何自定义标签的背景和颜色?

css - 如何在语义 UI 中的卡片之间生成内部单元格边界

javascript - 使用map方法返回一组新的数组

reactjs - 如何使用 React 将视频文件上传到 S3 存储桶

reactjs - 选择建议后如何关闭 vscode 添加自动补全 "={}"

javascript - React-Strap 的日期选择器

reactjs - React-Bootstrap 中 NavDropdown 中的 EventKeys

reactjs - 单击时更改按钮的样式

reactjs - 如何开发可重用的类似 Bootstrap 的组件