需求:消息提醒滚动展示 滑入暂停 移出继续滚动
import React, { useState, useEffect, useRef } from 'react';
import './index.less';
export default function WarringList(){
<!-- 初始列表 -->
const [list,setList]=useState([{id:1,data:1},{id:2,data:2},{id:3,data:3}])
<!-- 是否滚动 -->
const [isScrolle,setIsScrolle]=useState(true)
<!-- 速度阈值 -->
const speed=70
<!-- dom 滚动区域 -->
const warper=useRef()
<!-- 数据列表 -->
const childDom=useRef()
<!-- 无缝滚动 -->
const childDomCopy=useRef()
<!-- 自动滚动 -->
useEffect(()=>{
<!-- 复制数据 无缝滚动使用 -->
childDomCopy.current.innerHTML=childDom.current.innerHTML
<!-- 定时器 -->
let timer;
<!-- 是否滚动 true 滚动 -->
if(isScrolle){
timer=setInterval(()=>{
<!-- 如果距离顶部的高度不大于列表内容的高度 滚动-->
warper.current.scrollTop >= childDom.current.scrollHeight
? (warper.current.scrollTop = 0)
:warper.current.scrollTop++
},speed)
}
<!--false 清除定时器 不滚动-->
return () => {
clearInterval(timer);
};
},[isScrolle])
<!-- 是否滚动 传参 -->
const hoverHandler=(type)=>setIsScrolle(type)
return (
<>
<div ref={warper} className='parent'>
<div ref={childDom} className='child'> {list.map((item) => (
<div className="warning-box" key={item.id}
onMouseOver={()=> hoverHandler(false)}
onMouseLeave={() => hoverHandler(true)}>
<div className="warning-box">{item.data}</div>
</div>
))}
</div>
<div ref={childDomCopy} className='child'></div>
</div>
</>
)
`}``
less
.parent {
width: 100%;
height: 36px;
overflow-y: scroll;
scrollbar-width: none;
-ms-overflow-style: none;
}
.parent::-webkit-scrollbar {
display: none;
}
.child{
height: auto;
}
.warning-box{
height: 36px;
line-height: 36px;
}