React中useRef实现按钮控制横向滚动失效问题求助
问题排查与修复方案
核心问题
你同时给外层container(Grid组件)和内层productItemsContainer(div)设置了overflowX: scroll,导致滚动容器层级混乱:ref挂载的内层div实际没有产生横向溢出的条件,滚动行为被外层容器拦截,所以scrollLeft始终为0。
修复步骤
调整CSS样式,明确唯一滚动容器
- 移除内层
productItemsContainer的overflowX: scroll,让滚动行为由外层container负责 - 给内层flex容器设置
minWidth: 'max-content',确保内容能撑出外层容器宽度,触发横向滚动
- 移除内层
将ref挂载到正确的滚动容器
- 把ref从内层div转移到外层的Grid组件(即
container类对应的元素)
- 把ref从内层div转移到外层的Grid组件(即
修改后的完整代码
样式部分
const styles = () => ({ paper: { padding: '25px', borderRadius: '10px' }, title: { fontSize: '16px', fontWeight: 'bold', fontStyle: 'normal', lineHeight: 3, letterSpacing: 'normal', textAlign: 'left', }, container: { height: '110px', overflowX: 'scroll', // 可选:隐藏原生滚动条,不影响功能 scrollbarWidth: 'none', '&::-webkit-scrollbar': { display: 'none' } }, productItemsContainer: { display: 'flex', minWidth: 'max-content', // 确保内容撑开足够宽度 gap: '16px' // 可选:给产品项添加间距 } });
组件部分
const relatedProducts = ({ classes, products }) => { const scrollRef = useRef(null); const scroll = (scrollOffset) => { if (scrollRef.current) { scrollRef.current.scrollLeft += scrollOffset; console.log(scrollRef.current.scrollLeft); } }; return ( <Paper className={classes.paper}> <Typography className={classes.title} gutterBottom>Discover Products</Typography> <button onClick={() => scroll(-80)}>LEFT</button> <button onClick={() => scroll(+80)}>RIGHT</button> {/* ref挂载到外层滚动容器 */} <Grid className={classes.container} container direction="column" ref={scrollRef}> <Grid item> <div className={classes.productItemsContainer}> {products.map((product) => ( <RelatedProductItem key={product.item} product={product} /> ))} </div> </Grid> </Grid> </Paper> ); };
额外排查点
- 检查
RelatedProductItem组件是否设置了固定宽度,没有的话flex容器可能无法撑开足够宽度产生溢出 - 确保外层滚动容器的宽度被父元素限制(比如设置固定宽度或占满父容器),否则它会随内容宽度自适应,不会产生滚动
内容的提问来源于stack exchange,提问作者Kimbo
相关产品推荐
相关产品推荐

