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

相关推荐
清羽_ls2 小时前
React Hooks 核心规则&自定义 Hooks
前端·react.js·hooks
mapbar_front7 小时前
react项目开发—关于代码架构/规范探讨
前端·react.js
需要兼职养活自己8 小时前
react高阶组件
前端·react.js
今天周二8 小时前
vite 将react老项目中的没有兼容处理的写法转成兼容性写法
react.js
GISBox9 小时前
GISBox如何让GeoTIFF突破Imagery Provider加载限制?
react.js·json·gis
天蓝色的鱼鱼11 小时前
Next.js 渲染模式全解析:如何正确选择客户端与服务端渲染
前端·react.js·next.js
果粒chenl13 小时前
React学习(四) --- Redux
javascript·学习·react.js
LRH15 小时前
React 双缓存架构与 diff 算法优化
前端·react.js
中微子16 小时前
别再被闭包坑了!React 19.2 官方新方案 useEffectEvent,不懂你就 OUT!
前端·javascript·react.js
1in16 小时前
一文解析UseState的的执行流程
前端·javascript·react.js