You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React点击按钮控制div自动横向滚动实现图片轮播的方法

解决方案

第一步:修改styled-components配置,开启平滑滚动,隐藏原生滚动条

修改你的SecondContainer样式代码如下:

export const SecondContainer = styled.div`
    height:100%;
    width: 100vw;
    overflow-x: auto;
    background: black;
    display : flex;
    /* 新增以下内容 */
    scroll-behavior: smooth; /* 核心:开启平滑滚动动画 */
    /* 隐藏原生滚动条,避免用户手动拖动干扰 */
    &::-webkit-scrollbar {
        display: none;
    }
    -ms-overflow-style: none;
    scrollbar-width: none;
`

第二步:修改React组件逻辑,绑定滚动容器引用,控制滚动距离

修改你的FirstSection组件代码如下:

import React,{useState, useEffect, useRef} from 'react' // 新增引入useRef

import { ThirdContainer, SecondContainer, ButtonLeft, ButtonRight, ButtonTitle, Container, FirstRow, FirstTitle, SecondRow, SecondTitle, TitleContainer } from './FirstSectionStyled'

const FirstSection = ({bgData}) => {
    // 新增:创建滚动容器引用
    const scrollerRef = useRef(null)
    // 新增:记录当前展示的轮播索引
    const [currentIndex, setCurrentIndex] = useState(0)

    const nextSlide = () => {
        // 到达最后一张时停止轮播,也可以改成回到第一张实现循环
        if(currentIndex < bgData.length - 1) {
            setCurrentIndex(prev => prev + 1)
        }
    }
    const prevSlide = () => {
        // 到达第一张时停止轮播
        if(currentIndex > 0) {
            setCurrentIndex(prev => prev - 1)
        }
    }

    // 索引变化时触发滚动
    useEffect(() => {
        if(scrollerRef.current) {
            // 每张宽度是100vw,滚动距离 = 索引 * 视口宽度
            scrollerRef.current.scrollTo({
                left: currentIndex * window.innerWidth,
                behavior: 'smooth'
            })
        }
    }, [currentIndex, bgData.length])

    // 可选:监听窗口大小变化,自动修正滚动位置
    useEffect(() => {
        const handleResize = () => {
            if(scrollerRef.current) {
                scrollerRef.current.scrollLeft = currentIndex * window.innerWidth
            }
        }
        window.addEventListener('resize', handleResize)
        return () => window.removeEventListener('resize', handleResize)
    }, [currentIndex])

    return (
        <Container>
            <ButtonLeft onClick={prevSlide}/>
                {/* 把ref绑定到滚动容器上 */}
                <SecondContainer ref={scrollerRef} id="scroller">
                    {bgData.map((data,index) => (
                        <ThirdContainer key={data.id} backgroundImg = {data.backgroundImg}>
                            <FirstRow>
                                <TitleContainer>
                                    <FirstTitle>{data.firstTitle}</FirstTitle>
                                    <SecondTitle>{data.secondTitle}</SecondTitle>
                                    <ButtonTitle>Buy Now</ButtonTitle>
                                </TitleContainer>
                            </FirstRow>
                            <SecondRow>
                            </SecondRow>
                        </ThirdContainer>
                    ))
                    }
                </SecondContainer> 
            <ButtonRight onClick={nextSlide} />
        </Container>
    )
}

export default FirstSection

额外说明

如果需要实现无限循环轮播,可以在nextSlide里判断currentIndex === bgData.length -1时直接把索引设为0,prevSlide里判断currentIndex === 0时设为bgData.length -1即可。

内容的提问来源于stack exchange,提问作者Woppy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:09:03