import React from 'react';
/**
 * @刘丹: 横向滚动
 */
class Scroll extends React.Component {
  constructor() {
    super();
    this.state = {
      isScroll: false,
      ref: React.createRef(),
    };
  }
  componentDidMount() {
    if (this.state.ref.current) {
      this.initWidth();
    }
  }
  componentDidUpdate(prev) {
    if (prev.text !== this.props.text && this.state.ref.current) {
      this.initWidth();
    }   
  }
  initWidth = () => {
    const parentDom = this.state.ref.current.parentNode;
    if (!parentDom) {
      return;
    }
    const parentW = parentDom.offsetWidth - 0.8 * 2 * document.body.clientWidth / 100;
    this.setState({
      isScroll: this.state.ref.current.offsetWidth > parentW,
    });
  };
  render() {
    return (
      <div ref={this.state.ref}>
        <div className={this.state.isScroll
          ? this.props.isFast ? 'marquee fast' : 'marquee'
          : ''}
        >
          {this.props.text}
        </div>
     </div>
    );
  }
}

export default Scroll;
