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的图片数组,超过父容器的区域被隐藏。

相关推荐
Shinner欣儿10 小时前
React18 和 19 新特性结合看
前端·react.js
光影少年12 小时前
react navite环境与工程化
前端·react native·react.js
用户2986985301413 小时前
使用 JavaScript 在 React 中实现 Word 转 PDF
前端·javascript·react.js
专业抄代码选手18 小时前
01|从手写 DOM 到虚拟 DOM:把 UI 从“操作”变成“描述”
前端·javascript·react.js
专业抄代码选手18 小时前
03|React 为什么需要协调:比较两棵树,而不是重建页面
前端·javascript·react.js
YIAN18 小时前
告别等后端!React+Vite 前端独立开发全流程:接口封装 + Mock 方案 + 状态管理
前端·react.js·vite
werdedeage18 小时前
用 useReducer 管理多参考图生成器的前端状态
react.js·typescript
circuitsosk18 小时前
智能体任务拆解与执行:基于ReAct+Plan-and-Execute框架的行业Skill构建实录
前端·javascript·python·react.js·react·llm agent·智能体编排
zzzzzz31021 小时前
36K stars 的“酷炫组件”,到底该怎么用才不显得用力过猛?
前端·react.js·动效