我正在制作一个轮播应用,我想了解如何通过拖动来滚动轮播中的项目。我希望能够通过用鼠标拖动“carousel-content”div 的子项来滚动它们。
目前,“carousel-content-wrapper”是一个带有 overflow: scroll 的 flexbox 组件,在移动设备上通过触摸滑动它可以正常工作。但是,我希望能够在桌面上执行相同的操作 - 用鼠标轻扫项目,让项目跟随鼠标移动,就像您用手指滚动一样。
function Carousel(props) {
const {children} = props
const [index, setIndex] = useState(0)
const [array, setArray] = useState([])
const [length, setLength] = useState(children.length)
const mobile = window.innerWidth > 768 ? "false" : "true"
// setting up breakpoints for easy responsiveness
useEffect(() => {
setLength(children.length)
setArray(React.Children.toArray(children))
}, [children])
const next = () => {
if (index < (length-1)) {
setIndex(prevState => prevState + 1)
}
// sets the index to next if you are not on the last slide
}
const previous = () => {
if (index > 0) {
setIndex(prevState => prevState - 1)
}
// sets the index to be the previous if you are further than first slide
}
return (
<div className="carousel-outer-container" style={{
height: props.outerHeight,
width: props.outerWidth,
padding: props.outerPadding,
}}>
<div className="carousel-inner-container" style={{height: props.innerHeight, width: props.innerWidth}}>
<div className="carousel-wrapper"
>
{ index > 0 && <button className="left-arrow" onClick={previous}>
<
</button> }
<div className="carousel-content-wrapper" >
{ index < children.length - props.show && <button className="right-arrow" onClick={next}>
>
</button>}
{/* the sliding is done by the translateX below. it translates by (100% of the slides * the index of the slide) from the starting position. */}
<div className="carousel-content"
style={{transform: mobile === "false" && `translateX(-${index * 100 }%)`,
width: mobile === "false" && `${100 / props.show}%`}}
>
{children}
</div>
</div>
</div>
</div>
</div>
)
}
使这成为可能的最佳方法是什么?不使用外部包或库并使用钩子而不是类组件的解决方案会很棒。