Dwo*_*oro 3 carousel typescript reactjs
我正在使用 alice-carousel ( https://github.com/maxmarinich/react-alice-carousel/blob/master/README.md )制作轮播组件,但在自定义箭头时遇到问题。代码如下
export const Carousel: React.FC<CarouselProps> = ({text }) => {
const [activeIndex, setActiveIndex] = useState(0);
const items = ["item1","item2","item3"]
const slidePrev = () => {
activeIndex==0?(
setActiveIndex(items.length-1)):
setActiveIndex(activeIndex - 2);
};
const slideNext = () => {
activeIndex==items.length-1?(
setActiveIndex(0))
: setActiveIndex(activeIndex + 2)
};
return(
<div className="grid grid-cols-3">
<div className="col-span-2>
{text}
</div>
<div className="flex justify-end">
<button className="px-8" onClick={slidePrev}><ArrowL/></button>
<button className="px-8" onClick={slideNext}><ArrowR/></button>
</div>
<div className="col-span-3 px-10">
<AliceCarousel
mouseTracking
disableDotsControls
disableButtonsControls
activeIndex={activeIndex}
items={items}
responsive={responsive}
controlsStrategy="responsive"
autoPlay={true}
autoPlayInterval={5000}
infinite={true}
keyboardNavigation={true}
/>
</div>
</div>
)}
Run Code Online (Sandbox Code Playgroud)
上面的代码更改了activeIndex因此更改了项目的显示顺序,但它没有“幻灯片”动画。我已经查看了所使用的库中提供的示例,但似乎无法让它顺利滑动。我究竟做错了什么?
我鼓励您使用库的选项来降低实现的复杂性并阻止不需要的行为。
根据文档,有两个函数renderPrevButton和renderNextButton用于为图库上的上一个和下一个AliceCarousel项目呈现自定义组件(任何元素、图标、按钮等) 。
因此,不要使用自定义操作处理程序定义自定义按钮,而是将所需的组件传递给上述函数并为它们提供一些自定义样式。
export const Carousel: React.FC<CarouselProps> = ({text}) => {
const items = ["item1","item2","item3"]
return (
<div className="grid grid-cols-3">
<div className="col-span-2"> // ---> you forgot to add closing string quotation mark
{text}
</div>
<div className="col-span-3 px-10">
<AliceCarousel
mouseTracking
disableDotsControls
// disableButtonsControls // ---> also remove this
// activeIndex={activeIndex} // ---> no need to this anymore
items={items}
responsive={responsive}
controlsStrategy="responsive"
autoPlay={true}
autoPlayInterval={5000}
infinite={true}
keyboardNavigation={true}
renderPrevButton={() => {
return <p className="p-4 absolute left-0 top-0">Previous Item</p>
}}
renderNextButton={() => {
return <p className="p-4 absolute right-0 top-0">Next Item</p>
}}
/>
</div>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
注意:您需要disableButtonsControls从 中删除该选项AliceCarousel才能正确处理自定义按钮。此外,您不再需要使用该activeIndex选项,因为轮播会自动处理它们。
作为示例,我p通过 my 传递了一个元素,renderPrevButton没有任何onClick操作。您可以定义自定义图标、图像或任何元素并传递它们。
| 归档时间: |
|
| 查看次数: |
4500 次 |
| 最近记录: |