React - 实现走马灯组件

一、实现效果

二、源码分析

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

相关推荐

  1. js实现走马灯效果

    2024-06-08 03:30:03       40 阅读
  2. React实现抽屉组件

    2024-06-08 03:30:03       39 阅读
  3. React - 表单组件实现

    2024-06-08 03:30:03       39 阅读
  4. React 表单组件实现

    2024-06-08 03:30:03       40 阅读
  5. react实现组件通信的案例

    2024-06-08 03:30:03       19 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-08 03:30:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-08 03:30:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-08 03:30:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-08 03:30:03       20 阅读

热门阅读

  1. Flink Rest Basic Auth - 安全认证

    2024-06-08 03:30:03       11 阅读
  2. 安卓手机APP开发___设备管理概述

    2024-06-08 03:30:03       11 阅读
  3. Gnu/Linux 系统编程 - 如何获取帮助及一个演示

    2024-06-08 03:30:03       9 阅读
  4. C#朗读语音

    2024-06-08 03:30:03       8 阅读
  5. 第3章 列表简介

    2024-06-08 03:30:03       12 阅读
  6. MySQL数据库(7)

    2024-06-08 03:30:03       10 阅读
  7. 快慢指针算法举例

    2024-06-08 03:30:03       8 阅读
  8. pytest +allure在测试中的应用

    2024-06-08 03:30:03       10 阅读
  9. Python笔记 - Lambda表达式

    2024-06-08 03:30:03       10 阅读
  10. Kotlin 注解

    2024-06-08 03:30:03       12 阅读