reactjs - 允许手风琴一次只打开一个
问题描述
我正在用 react spring 创建一个手风琴,手风琴已经准备好并且工作正常,但是我不能让手风琴同时打开一个项目,现在同时打开所有三个项目,我希望只能打开一个。
这是代码和-> https://codesandbox.io/s/prod-sun-ttix7?file=/src/App.tsx
解决方案
您只需将打开状态拉到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 。
推荐阅读
- flutter - 如何在 Flutter 中更改 DropdownButton 的选定索引
- delphi - 在 Delphi 中为 TObject 分配一个属性
- react-native - 获得未定义不是一个对象(评估'props.navigation.addListener')
- java - 如何修复“列表类型不是通用的;它不能用参数参数化
“黄瓜硒JAVA中的错误 - python - python类的执行顺序
- javascript - 对象不使用扩展运算符替换
- python-3.x - 有没有办法在 flask-socketio 事件中修改烧瓶会话?
- java - 如何通过 TestNG 参数化配置环境 URL?
- bootstrap-4 - How can I center hr divider (in bootstrap 4)
- tfs - 无法从 Visual Studio Market Place 访问测试管理器(Azure 测试计划)