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

相关推荐
ZengLiangYi14 小时前
React 事件订阅的稳定引用问题:从 useEffect 到 useEffectEvent
react.js
是你的小橘呀19 小时前
TypeScript在React项目中的实战应用指南
react.js
leolee1820 小时前
react redux 简单使用
前端·react.js·redux
gxp1231 天前
初学React:请求数据参数未更新 && 数据异步状态更新问题
react.js
leolee182 天前
Redux Toolkit 实战使用指南
前端·react.js·redux
bluceli2 天前
React Hooks最佳实践:写出优雅高效的组件代码
前端·react.js
青青家的小灰灰2 天前
金三银四面试官最想听的 React 答案:虚拟 DOM、Hooks 陷阱与大型列表优化
前端·react.js·面试
光影少年2 天前
在 React 中,什么情况下需要用 useCallback 和 useMemo?它们的区别是什么?
前端·react.js·掘金·金石计划
符方昊3 天前
React 19 对比 React 16 新特性解析
前端·react.js
不会敲代码13 天前
前端组件化样式隔离实战:React CSS Modules、styled-components 与 Vue scoped 对比
css·vue.js·react.js