首页 > 解决方案 > 允许手风琴一次只打开一个

问题描述

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

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

标签: reactjsreact-springresize-observerreact-resize-observer

解决方案


您只需将打开状态拉到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 。


推荐阅读