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

相关推荐
FogLetter1 小时前
手写useInterval:告别闭包陷阱,玩转React定时器!
前端·react.js
用户479492835691512 小时前
React DevTools 组件名乱码?揭秘从开发到生产的代码变形记
前端·react.js
开发者小天17 小时前
React中使用useParams
前端·javascript·react.js
GISer_Jing21 小时前
跨端框架对决:React Native vs Flutter深度对比
flutter·react native·react.js
WYiQIU1 天前
大厂前端岗重复率极高的场景面试原题解析
前端·javascript·vue.js·react.js·面试·状态模式
lichenyang4531 天前
从零到一:编写一个简单的 Umi 插件并发布到 npm
前端·react.js·前端框架
FogLetter1 天前
从零实现一个低代码编辑器:揭秘可视化搭建的核心原理
前端·react.js·低代码
探索宇宙真理.1 天前
React Native Community CLI命令执行 | CVE-2025-11953 复现&研究
javascript·经验分享·react native·react.js·安全漏洞
. . . . .1 天前
React底层原理
javascript·react.js
Jacky-0081 天前
Node + vite + React 创建项目
前端·react.js·前端框架