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

使用Material UI+React创建可滚动横向卡片列表遇阻,求解决方案

实现Material UI横向可滚动卡片列表

你的代码里有几个关键样式问题导致无法实现横向滚动,调整以下几点即可解决:

关键修改点

  • 外层容器去掉flexWrap: 'wrap'(这会让卡片换行,无法触发横向滚动),同时把overflow: 'hidden'改为overflowX: 'auto'(只在横向溢出时显示滚动条)
  • 保持Grid容器的flexWrap: 'nowrap',确保卡片始终横向排列

修改后的完整代码

return (
  <div style={{ 
    display: 'flex',
    justifyContent: 'flex-start', // 改为flex-start,让卡片从左侧开始排列
    overflowX: 'auto', // 横向溢出时显示滚动条
    width: 1200,
    padding: '16px 0' // 可选,给滚动区域上下加内边距优化体验
  }}>
    <Grid container spacing={3} style={{flexWrap: 'nowrap'}}>
      {data.map((item, index) => { // 变量名避免重复,将循环变量改为item
        const { Title, Summary } = item;
        return (
          <Grid item key={index}> {/* 必须添加唯一key属性,避免React渲染警告 */}
            <Card sx={{ width: 300 }}>
              <CardMedia
                sx={{ height: 140 }}
                image="/static/images/cards/contemplative-reptile.jpg"
                title="green iguana"
              />
              <CardContent>
                <Typography gutterBottom variant="h5" component="div">
                  {Title}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  {Summary}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        );
      })}
    </Grid>
  </div>
);

额外优化提示

  • 优先使用数据中的唯一ID作为key属性值(而非index),提升React渲染性能
  • 如果需要隐藏滚动条但保留滚动功能,可以给外层容器添加以下样式:
    sx={{
      msOverflowStyle: 'none',
      scrollbarWidth: 'none',
      '&::-webkit-scrollbar': {
        display: 'none'
      }
    }}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:33:28