我正在学习使用 Material-ui 和 React 创建网站。
我想创建一个可折叠的网格,其中一些行根据页面状态折叠/展开。
当我在 Grid 布局中添加折叠组件时,Grid 布局被破坏了。
我在这里创建了一个示例代码(https://codesandbox.io/embed/jolly-golick-3lwt5)用于演示。
在这里,您看到折叠的部分(当前条件“展开”未按预期显示。
我在这里做错了什么吗?
这就简单多了,但只显示了折叠动画。
<Grid item xs={3} style={{ display: showCollapse ? "block" : "none" }}>
<Collapse in={showCollapse}>
<Button>Button</Button>
</Collapse>
</Grid>
这对我有用:
import MuiCollapse from '@material-ui/core/Collapse'
import Grid from '@material-ui/core/Grid'
const GridItemXs12 = (props) => <Grid item xs={12} {...props} />
const Collapse = (props) => {
const classes = useCollapseStyles()
return (
<MuiCollapse
component={GridItemXs12}
classes={{
hidden: classes.hidden,
}}
{...props}
>
{/* This spacing has to match with the one in the container
outside the collapse */}
<Grid container spacing={2}>
{props.children}
</Grid>
</MuiCollapse>
)
}
const useCollapseStyles = makeStyles({
hidden: {
// The grid item's padding normally balances with the negative padding
// of the container outside the Collapse.
// But when the collapse hides its content, the padding of the item
// is still taking up space, creating an unwanted space.
// The 'hidden' style rule is only applied when the collapse finishes
// hiding its content
padding: '0 !important',
},
})
然后使用这个习俗
Collapse
作为Grid container
的直系后代
const MyComponent = () => {
return (
<Grid container spacing={2}>
<Collapse in={/* your controlled variable */}>
<Grid item xs={12}>
The content inside this grid item looks as if the item were
directly inside the container
</Grid>
</Collapse>
</Grid>
)
}
这里是使用这种方法的示例代码的修改版本 https://codesandbox.io/s/exciting-hodgkin-rk2wv,我在主 div 中添加了一个 onClick 处理程序,以便单击其中的任意位置切换折叠。
此解决方案假设您想要折叠占据容器整个宽度的东西。它还假定您希望在该容器中有一些间距(实际上,没有间距,网格根本不会中断)。此外,当应用 padding 样式时,动画中有一些卡顿,间距越大,它就越明显。
希望还不算太晚
只加
style={{width: "100%"}}
或使用
<Collapse sx={{
[`&.${collapseClasses.root}`]: {
width: "100%",
},
}}>