如何为React flex滑块添加左右箭头,无需按Shift即可横向滑动
实现方案
第一步:修改Row.js代码
首先引入useRef钩子,创建滑块节点引用,添加滚动控制函数和箭头按钮:
import { useRef } from 'react'; // 组件内部代码 const Row = () => { const sliderRef = useRef(null); // 向左滚动函数,每次滚动距离可自行调整 const scrollLeft = () => { sliderRef.current.scrollLeft -= 500; }; // 向右滚动函数,每次滚动距离可自行调整 const scrollRight = () => { sliderRef.current.scrollLeft += 500; }; return ( <React.Fragment> <div className="row"> <h2>Top Rated</h2> <button className="slider-arrow slider-arrow-left" onClick={scrollLeft}><</button> <div className="row_thumbnails" ref={sliderRef}> {videos.map((item) => ( <img onClick={() => handleClick(item.id)} key={item.id} className="row_thumbnail rowLarge" src={item.thumbnail} alt={item.title} /> ))} </div> <button className="slider-arrow slider-arrow-right" onClick={scrollRight}>></button> </div> </React.Fragment> ); }
第二步:修改Row.css代码
给外层容器添加相对定位,新增箭头按钮的样式:
/* 修改原有.row样式,添加相对定位 */ .row { color: white; margin-left: 20px; position: relative; } .row_thumbnails { display: flex; overflow-y: hidden; overflow-x: scroll; scroll-behavior: smooth; padding: 20px; } .row_thumbnails::-webkit-scrollbar { display: none; } .row_thumbnail { object-fit: contain; width: 246px; height: 138px; margin-right: 15px; transition: transform 450ms; } .rowLarge { width: 300px; height: 150px; } .row_thumbnail:hover { transform: scale(1.08); } .row6 { margin-bottom: 10rem; } /* 新增箭头样式 */ .slider-arrow { position: absolute; top: 50%; transform: translateY(-50%); z-index: 10; width: 40px; height: 40px; border: none; border-radius: 50%; background-color: rgba(0,0,0,0.7); color: white; font-size: 20px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: background-color 0.3s; } .slider-arrow:hover { background-color: rgba(0,0,0,0.9); } .slider-arrow-left { left: 10px; } .slider-arrow-right { right: 10px; }
如果需要调整单次滚动的距离,修改scrollLeft/scrollRight函数里的数值即可,也可以根据缩略图的宽度动态计算滚动距离,实现每次滚动固定数量的卡片。如果需要优化边界体验,可以在滚动函数中添加判断,当滑块滚动到最左侧时隐藏左箭头,滚动到最右侧时隐藏右箭头。
内容的提问来源于stack exchange,提问作者chaitu605
相关产品推荐
相关产品推荐

