You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何隐藏Material UI Grid项并实现其余项平滑滑入的过渡动画效果

解决方案

核心问题

display: none 不支持CSS过渡动画,因为该属性会直接将元素从渲染树中移除,没有中间过渡状态,所以你看不到平滑消失、其余项补位的效果。

参考实现效果如下:
筛选动效参考

实现方案

你已经引入了MUI自带的Grow过渡组件,配合Grid项的样式过渡即可实现需求:所有商品Grid项始终保留在DOM中,未命中筛选的商品先执行淡出+收起动画,再将宽高、边距缩为0,自然带动其余网格项平滑补位。

修改代码

你只需要调整renderProducts部分的逻辑即可,修改后代码如下:

const renderProducts = () => (
  <>
    <Container maxWidth="lg" >
      <Grid
        container
        direction="row"
        spacing={3}
        sx={{
          pl: !mobile && menu && "300px",
          transition: ".3s",
        }}>
        {items.map((product) => {
          // 判断当前商品是否命中筛选
          const isMatched = newItems.some(newItem => newItem.id === product.id)
          return (
            <Grid 
              item 
              xs={12} 
              sm={6} 
              md={4} 
              lg={3} 
              key={product.id}
              sx={{
                transition: 'all 0.3s ease',
                // 未命中时将宽高、边距、内边距都缩为0,溢出隐藏不占位
                ...(!isMatched && {
                  opacity: 0,
                  width: 0,
                  height: 0,
                  padding: 0,
                  margin: 0,
                  overflow: 'hidden',
                })
              }}
            >
              {/* 用Grow组件控制内容的显隐动画,包一层div避免ref警告 */}
              <Grow in={isMatched} timeout={300}>
                <div>
                  <Product product={product} disable={isMatched} />
                </div>
              </Grow>
            </Grid>
          )
        })}
      </Grid>
    </Container>
  </>
);

效果说明

筛选触发时,未命中的商品会先淡出同时高度收缩,Grid项的边距同步过渡为0,周围的网格项会自然平滑滑动到空白位置补位。动画时长统一设为300ms,你可以根据需求调整transition和timeout的数值,保持两者一致即可。

内容的提问来源于stack exchange,提问作者Elfandrei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:45:04