更新时间:2023-12-02 19:46:04
您想将所选项目存储在状态变量中,然后使用 React.Children.map
遍历子项以遍历子项.如果子节点的索引是selectedNavItem
中存储的索引,则返回null
.React 不会在您的 DOM 中呈现 null
,因此它不会显示任何内容.如果你想渲染一个看起来不同的组件,你也可以将一个 className 属性传递给很容易被选中的子组件.
You want to store the selected item in a state variable and then iterate throug children using React.Children.map
to iterate through children. If the index of the child is the stored index in selectedNavItem
, return null
. React won't render null
in your DOM, so it won't display anything. If you wanted to render a component that looks different you can also pass a className prop to the child that is selected quite easily.
const NavigationDrawer = (props) => {
// the children of this component would be <NavigationDrawerItem /> components.
const {
children,
} = props
// the selected nav item
const [selectedNavItem, setSelectedNavItem] = React.useState(null)
// the index of the nav item is passed here and stored in the state variable
const handleNavItemOnClick = (index) => {
setSelectedNavItem(index)
}
}, [children])
return <Drawer>
{
// iterate over the children components
return React.Children.map(child, index) => {
return index !== selectedNavItem
// the first param of React.cloneElement is the component to clone, in our
// case a child component. The second param is the props to pass that cloned
// component.
? React.cloneElement(child, {
onClick: () => handleNavItemClick(index)
})
: null
})
}
</Drawer>
}