React - 实现走马灯组件

一、实现效果

二、源码分析

javascript 复制代码
import {useRef, useState} from "react";

export const Carousel = () => {
    const images = [{
        id: 3, url: 'https://sslstage3.sephorastatic.cn/products/2/4/6/8/1/6/1_n_new03504_100x100.jpg'
    }, {
        id: 1, url: 'https://sslstage2.sephorastatic.cn/products/2/4/5/3/5/8/1_n_new03504_100x100.jpg'
    }, {
        id: 2, url: 'https://sslstage1.sephorastatic.cn/products/2/4/5/2/8/2/1_n_new03504_100x100.jpg'
    }];
    const [index, setIndex] = useState(0);

    const refreshInterval = useRef(null)
    if (refreshInterval.current === null) {
        refreshInterval.current = setInterval(() => setIndex(val => (val + 1) % images.length), 3000)
    }

    const containerStyle = {
        width: '100px', height: '100px', overflow: "hidden", border: '1px solid red',
    }

    const imageStyle = {
        width: 100 * images.length + 'px',
        transition: 'transform 1.5s ease',
        position: 'relative',
        left: -1 * index * 100 + 'px',
    }
    return (
        <div>
            <div style={containerStyle}>
                <div style={imageStyle}>
                    {images.map(item =>
                        <div style={{display: 'inline-block'}}>
                            <img width={100} height={100} key={item.id} src={item.url} alt='product'/>
                        </div>
                    )}
                </div>
            </div>

            <div>
                <button onClick={() => setIndex(val => (val - 1) % images.length)}>pre</button>
                {index + 1}
                <button onClick={() => setIndex(val => (val + 1) % images.length)}>next</button>
            </div>
        </div>)
}

本文给的代码是基于定位实现,父容器是显示区域,子容器是inline的图片数组,超过父容器的区域被隐藏。

相关推荐
李明卫杭州15 小时前
React 复合事件系统对比解析
前端·javascript·react.js
白雾茫茫丶17 小时前
Vibecoding 一个主题切换动画库:13 种揭幕方式
前端·vue.js·react.js
西瓜太郎49918 小时前
别再手算 Token 成本:用 React 状态机做一个可追溯的模型费用计算器
react.js·typescript
右耳朵猫AI1 天前
Web前端周刊2026W37 | Shopify 转原生、React 编译 Rust 化、Vitest 5.0、Rslib 1.0
前端·javascript·react.js·typescript·node.js
csj501 天前
前端基础之《React(13)—表单绑定、列表渲染》
前端·react.js
csj501 天前
前端基础之《React(12)—条件渲染》
前端·react.js
晚安日记wanna2 天前
SSR 为什么不适合登录态从水合冲突到缓存串号
前端·react.js·面试
liangshanbo12153 天前
React useEffect 与 useLayoutEffect 面试题整理
前端·javascript·react.js
liangshanbo12153 天前
React useState 函数式更新面试题整理
前端·react.js·前端框架
光影少年3 天前
react navite process.nextTick 和 Promise.then 的执行顺序
前端·react native·react.js