ts 封装轮播列表组件(循环滚动) 实现方案

858 阅读1分钟

参考 github.com/WayneVN/ks-…

import React, { Component } from 'react';
import './index.scss';

interface Props {
  content: any,
  height?: number,
  speed?: number,
}
export default class UnlimitedMarquee extends Component<Props> {


  componentDidMount() {
    const { speed = 50, height = 205  } = this.props;
    const wrap = this.refs.wrap as HTMLElement;
    const scrollDiv1 = this.refs.content1 as HTMLElement;
    const scrollDiv2 = this.refs.content2 as HTMLElement;
    wrap.style.height = height + 'px';
    
    function Marquee() {
      if (scrollDiv2.offsetHeight === wrap.scrollTop) {
        wrap.scrollTop -= scrollDiv1.offsetHeight;
      }
      wrap.scrollTop ++;
    }

    let MyMar = setInterval(Marquee, speed);
    wrap.onmouseover = function StartScroll() {
      clearInterval(MyMar);
    };

    wrap.onmouseout = function StopScroll() {
      MyMar = setInterval(Marquee, speed);
    };
  }

  render() {
    return (
      <div>
        <div ref="wrap" className="wrap">
          <div ref="content1" className="content-box">
            {this.props.content}
          </div>
          <div ref="content2" className="content-box">
            {this.props.content}
          </div>
        </div>
      </div>
    );
  }
}
.wrap,
.content-box {
  overflow: hidden;
}

使用方式

<Scroll content={
  <ul>
    <li>新闻1</li>
    <li>新闻2</li>
    <li>新闻3</li>
    <li>新闻4</li>
    <li>新闻5</li>
    <li>新闻6</li>
    <li>新闻7</li>
    <li>新闻8</li>
    <li>新闻9</li>
    <li>新闻10</li>
    <li>新闻11</li>
  </ul>
}
/>