【问题标题】:Allow accordion to only open one at a time允许手风琴一次只打开一个
【发布时间】:2021-12-03 19:52:53
【问题描述】:

我正在使用 react spring 创建一个手风琴,手风琴已经准备好并且工作正常,但我无法让手风琴同时打开一个项目,现在同时打开所有三个项目,我希望只能打开一个。

这里是代码和 -> https://codesandbox.io/s/prod-sun-ttix7?file=/src/App.tsx

【问题讨论】:

  • 请记住,您的帖子应该有自己的优点:即使您有可以链接到的工作代码,only add links in addition to 在您的帖子中也有 minimal reproducible example 代码。理想情况下作为可运行的 sn-p,但至少作为人们可以查看的代码,以便他们可以回答您的问题,以便未来的访问者可以立即判断他们找到您的帖子的问题是否与他们的问题相同自己的问题。关于 SO 的问题不仅仅是“现在帮助你”,而是“帮助现在和未来的每个人解决这个问题”=)

标签: reactjs react-spring resize-observer react-resize-observer


【解决方案1】:

您只需将打开状态拉入App 组件并使用键或索引作为(打开)指示器,如下所示:

应用组件

function App() {
  const [openKey, setOpenKey] = useState()

  const handleToggle = key => {
    setOpenKey(openKey !== key ? key : null)
  }

  return (
    <Container>
      {data &&
        data.map(({ name, content }) => (
          <ServiceItem
            key={name}
            name={name}
            content={content}
            toggle={handleToggle}
            open={openKey === name}
          />
        ))}
    </Container>
  );
}

ServiceItem 组件

const ServiceItem = ({ name, content, toggle, open }: ServiceItemProps): JSX.Element => {
  return (
    <div key={name}>
      <Item onClick={() => toggle(name)}>
        <Text className="text-15 regular laptop:text-20 laptop:regular">
          {name}
        </Text>
        <Icon className="text-15 regular laptop:text-20 laptop:regular">
          {!open ? "+" : "-"}
        </Icon>
      </Item>
      <Expandable open={open}>
        <ContentContainer>
          <React.Fragment key={name}>
            <Value>{content}</Value>
          </React.Fragment>
        </ContentContainer>
      </Expandable>
    </div>
  );
};

这是一个工作示例:https://codesandbox.io/s/infallible-banzai-fnncw

【讨论】:

    猜你喜欢
    • 2016-10-11
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    相关资源
    最近更新 更多