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

相关推荐
学前端搞口饭吃4 分钟前
React props的使用
前端·javascript·react.js
kk不中嘞18 小时前
浅谈前端框架
前端·vue.js·react.js·前端框架
小鱼儿亮亮1 天前
二、React基础精讲:编写TodoList、事件绑定、JSX语法、组件之间传值
前端·react.js
小鱼儿亮亮1 天前
五、Redux进阶:UI组件、容器组件、无状态组件、异步请求、Redux中间件:Redux-thunk、redux-saga,React-redux
前端·react.js
wordbaby1 天前
解锁时光机:用 React Hooks 轻松实现 Undo/Redo 功能
前端·react.js
LFly_ice1 天前
学习React-9-useSyncExternalStore
javascript·学习·react.js
醉方休1 天前
React中使用DDD(领域驱动设计)
前端·react.js·前端框架
学习3人组1 天前
React 样式隔离核心方法和最佳实践
前端·react.js·前端框架
乖女子@@@1 天前
React笔记_组件之间进行数据传递
javascript·笔记·react.js
Zacks_xdc1 天前
【前端】使用Vercel部署前端项目,api转发到后端服务器
运维·服务器·前端·安全·react.js