React Material-UI Grid组件如何从数组生成子项并添加横向滚动条
实现方案
你可以通过以下修改同时满足批量生成Grid项和横向滚动的需求:
核心修改点
- 给外层Grid容器设置
flexWrap: "nowrap",禁止子项自动换行,所有Grid item保持在同一行排列 - 外层容器新增
overflowX: "auto",内容超出容器宽度时自动显示横向滚动条 - 给每个Grid item设置
flexShrink: 0,避免子项被自动压缩宽度 - 使用数组
map方法遍历你的业务数据,批量生成Grid item节点,注意绑定唯一key属性
完整TSX代码示例
import React from 'react'; import { Grid, Box } from '@mui/material'; // 定义你的列表项数据类型 interface ListItemType { id: string | number; content: string; // 其他自定义字段... } const YourComponent: React.FC = () => { // 你的业务数据数组 const itemList: ListItemType[] = [ { id: 1, content: '内容1' }, { id: 2, content: '内容2' }, { id: 3, content: '内容3' }, { id: 4, content: '内容4' }, { id: 5, content: '内容5' }, { id: 6, content: '内容6' }, // 更多数据... ]; return ( <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start" sx={{ flexWrap: 'nowrap', overflowX: 'auto', // 可选:隐藏滚动条样式(如果需要) // '&::-webkit-scrollbar': { display: 'none' }, // '-ms-overflow-style': 'none', // 'scrollbar-width': 'none', }} > {itemList.map(item => ( <Grid item xs={5} key={item.id} sx={{ flexShrink: 0 }} > <Box m={5} pl={10}> {item.content} </Box> </Grid> ))} </Grid> ); }; export default YourComponent;
内容的提问来源于stack exchange,提问作者Peter Penzov
相关产品推荐
相关产品推荐

