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

相关推荐
太子釢6 小时前
React 函数组件与 Hook 实践指南
前端·react.js
liangshanbo12157 小时前
面试题:React 中 Lane 和 Scheduler 是怎么配合的?
前端·react.js·前端框架
liangshanbo12157 小时前
React面试题:Hooks 为什么不能在分支和循环里面写?
前端·javascript·react.js
FungLeo7 小时前
成为全栈·Next.js 网站前台篇·响应式、可访问性与错误状态:内容站不能只验桌面首页
react.js·响应式设计·next.js·移动端适配·成为全栈·web 可访问性
ss2738 小时前
AI全栈实战 | 3.5-01 Python 全栈前端最小集:不会 React 也能做出能看的后台,关键就一条线
前端·python·react.js
记得开心一点嘛1 天前
Trellora:基于 Electron、React 和本地知识库的 AI 知识工作台
人工智能·react.js·electron
500841 天前
React Native for OpenHarmony 实战:三方库 react-native-url-polyfill 的鸿蒙化适配指南
javascript·react native·react.js·性能优化·electron·harmonyos
500841 天前
React Native for OpenHarmony 实战:三方库 react-native-volume-control 的鸿蒙化适配指南
javascript·react native·react.js·electron·harmonyos
薛一半1 天前
React-Redux三重优化实战揭秘
javascript·vue.js·react.js
薛一半3 天前
React-Redux核心原理与容器组件实战
前端·javascript·react.js