【问题标题】:React Material-ui - Collapse on Grid breaks GridReact Material-ui - 在网格上折叠打破网格
【发布时间】:2019-11-28 14:16:21
【问题描述】:

我正在学习使用 Material-ui 和 React 创建一个网站。

我想创建一个可折叠的网格,其中一些行根据页面的状态折叠/展开。

当我在 Grid 布局中添加折叠组件时,Grid 布局被破坏。

我在这里创建了一个示例代码 (https://codesandbox.io/embed/jolly-golick-3lwt5) 用于演示。

在这里,您会看到折叠部分(当前条件为“展开”的部分未按预期显示。

我在这里做错了吗?

【问题讨论】:

  • Collapse 在其子项 (container, wrapper, and wrapperInner) 周围添加 three layers of divs。容器Grid 和项目Grid 之间的这些附加层将阻止Grid 的flexbox 布局正常工作。在仍然使用 Collapse 的同时可能获得您想要的外观,但它可能简单。

标签: 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%"}}
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2021-02-04
      • 2023-02-01
      • 2017-09-14
      • 2016-09-16
      • 2021-06-06
      • 1970-01-01
      • 2019-02-06
      • 2014-09-11
      相关资源
      最近更新 更多