1 需求
在开发项目的时候,从服务端获取到数据列表后,展示给用户看:需要实现数据自动滚动效果,怎么实现呢?如下图所示:2 实现
把上面需要实现的功能写成一个组件
1.需求
在开发项目的时候,从服务端获取到数据列表后,展示给用户看:需要实现数据自动滚动效果,怎么实现呢?如下图所示:
2.实现
把上面需要实现的功能写成一个组件,页面直接调用该组件即可,代码如下:
要引入组件页面的代码:
import Scroll from "../../components/Scroll"; const Index = () => { return ( <div class={style.main}> <Scroll /> </div> ) } export default Index;
组件:
import style from "./style.less"; import React, { useEffect, useRef, useState } from "react"; const Scroll = () => { const timer = useRef(null); //这里的数据是通过服务端api接口获取的 const marqueeList = [ { phone: "155****1111", content: "签到获取", money: 12.22, }, { phone: "151****1111", content: "签到获取", money: 2, }, { phone: "152****1111", content: "签到获取", money: 2.22, }, ... ]; //是否滚动 const [isScrolle, setIsScrolle] = useState(true); //滚动速度,值越小,滚动越快 const scrollSpeed = 100; const warper = useRef(); //原数据 const childDom = useRef(); //拷贝数据 const childDomCopy = useRef(); //鼠标移动,移除方法 const hoverHandler = (flag) => setIsScrolle(flag); useEffect(() => { // 设置轮播滚动多拷贝一层,让它无缝滚动 childDom.current.innerHTML = childDomCopy.current.innerHTML; if (isScrolle) { if (timer.current) { clearInterval(timer.current); } timer.current = setInterval(() => { warper.current.scrollTop >= childDom.current.scrollHeight ? (warper.current.scrollTop = 0) : warper.current.scrollTop++; }, scrollSpeed); } return () => { clearInterval(timer.current); }; }, [isScrolle]); return ( <div class={style.content}> <div class={style.parent} ref={warper}> <div class={`${style.ul_scoll}`} ref={childDomCopy}> {marqueeList.map((value, index) => ( <li style={{backgroundColor: index % 2 == 0 ? "#S1AAAA" : "#ABCDEF"}} key={value} onMouseOver={() => hoverHandler(false)} onMouseLeave={() => hoverHandler(true)} > <div class={style.li_intro}> <div> {value.phone} </div> <div> {value.content} </div> <div class={style.li_money_intro}> <div class={style.li_money}> +{value.money} </div> <div class={style.li_rmb}> RMB </div> </div> </div> </li> ))} </div> <div class={`${style.ul_scoll}`} ref={childDomCopy}></div> </div> </div> ); }; export default Scroll;
css:
.content { width: 100%; height: 14.16rem; overflow: hidden; position: relative; margin: auto; } .parent { top: 1rem; position: relative; height: 11.16rem; overflow: hidden; line-height: 2.5rem; overflow-y: scroll; scrollbar-width: none; -ms-overflow-style: none; } .parent::-webkit-scrollbar { display: none; } .ul_scoll li { width: 100%; height: 2.5rem; font-size: 0.9rem; font-weight: bold; text-align: center; letter-spacing: 0.025rem; line-height: 2.5rem; color: red; } .li_intro { color: #205F59; font-weight: 930; flex-direction: row; align-items: center; justify-content: space-between; display: flex; padding-left: 0.25rem; padding-right: 0.25rem; } .li_money_intro { display:flex; color: #39B54A; } .li_oney { font-size: 1rem; } .li_rmb { color:#FF6000; margin-left:0.8rem; font-size: 0.8rem; }
这样就能够实现数据不停滚动了
到此这篇关于react实现列表滚动组件的文章就介绍到这了,更多相关react列表滚动组件内容请搜索好代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好代码网!