【问题标题】:React Material-ui - Collapse on Grid breaks GridReact Material-ui - 在网格上折叠打破网格
【发布时间】:2019-11-28 14:16:21
【问题描述】:
【问题讨论】:
标签:
reactjs
grid
material-ui
collapse
【解决方案1】:
这对我有用:
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 处理程序,以便单击其中的任意位置来切换折叠。
此解决方案假定您想要折叠占据整个容器宽度的东西。它还假设您希望在该容器中有一些间距(实际上,如果没有间距,网格根本不会中断)。此外,当应用填充样式时,动画中会出现一些卡顿,间距越大,越明显。
【解决方案2】:
这要简单得多,但只显示折叠动画。
<Grid item xs={3} style={{ display: showCollapse ? "block" : "none" }}>
<Collapse in={showCollapse}>
<Button>Button</Button>
</Collapse>
</Grid>
【解决方案3】:
希望还不算晚
只添加
style={{width: "100%"}}