如何在map()函数中调整Material UI时间线内Grid元素的左右排列位置
问题根因
你原先定义的Grid类下的&:nth-child(2n+1)选择器无法生效,因为每个Grid容器都包裹在独立的TimelineItem节点中,不存在同级的Grid兄弟节点,无法匹配到偶数序列的内容容器。
解决方案1:利用map的下标动态控制flex方向
直接在循环时通过下标判断奇偶,动态修改Grid的flexDirection属性,不需要修改CSS选择器,修改后的JSX代码如下:
<Timeline align="alternate"> {/* 取map的第二个参数为下标idx */} {result.map((item, idx) => { return ( <TimelineItem className={classes.timelineStyle}> <TimelineOppositeContent> <Typography variant="body2" color="textSecondary"> {item.sif_date} </Typography> </TimelineOppositeContent> <TimelineSeparator> <TimelineDot className={classes.dot}> <LaptopMacIcon/> </TimelineDot> <TimelineConnector /> </TimelineSeparator> <TimelineContent> <Paper elevation={3} className={classes.paper}> {/* 动态判断flex方向 */} <Grid container style={{ display: 'flex', flexWrap: 'nowrap', flexDirection: idx % 2 === 0 ? 'row' : 'row-reverse' }}> <Grid item> <Typography variant="h6" component="h1"> {item.sif_titre} </Typography> <Typography style={{fontSize: 'smaller'}}> {item.sif_msg} </Typography> </Grid> <Grid item> <Zoom overlayBgColorStart='rgba(73, 80, 87, 67)' overlayBgColorEnd='rgba(73, 80, 87, 67)' zoomMargin={100}> <img src={item.sif_image} alt={item.sif_image} className={classes.img} style={{maxWidth: 200, maxHeight: 200}}/> </Zoom> </Grid> </Grid> </Paper> </TimelineContent> </TimelineItem> ) })} </Timeline>
解决方案2:通过CSS选择器匹配奇偶TimelineItem
不需要修改JSX逻辑,直接修改makeStyles里的样式规则,匹配偶数位的TimelineItem下的Grid容器即可:
const useStyles = makeStyles((theme) => ({ paper: { padding: '6px 16px', textAlign: 'center', backgroundColor: 'white !important', display: 'flex' }, secondaryTail: { backgroundColor: theme.palette.secondary.main, }, img : { flex: 1, resizeMode: 'contain', }, dot : { backgroundColor: '#ef9700' }, timelineStyle: { padding: '0px 300px !important', // 匹配偶数项timelineItem下的Grid容器,反转方向 '&:nth-child(even) .MuiGrid-container': { flexDirection: 'row-reverse' } }, Grid: { display: 'flex', flexWrap: 'nowrap', flexDirection: 'row', } }));
内容的提问来源于stack exchange,提问作者Quentin
相关产品推荐
相关产品推荐

