React-native/React 公告滚动组件(原生代码)

编写不易, 希望大家点赞

import React, {PureComponent} from 'react';
import {Animated, Easing, View} from 'react-native';

export default class NoticeScroll extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      newChildren: this.props.children,
    };
    this.animation = new Animated.Value(0);
    this.direction = this.props.direction === 'vertical' ? 'height' : 'width';
    this.transationValue = this.props.styles[this.direction];
    this.key = 0;
    this.arr = [];
  }

  startAnimation() {
    const meter = this.props.meter || 0;
    Animated.timing(this.animation, {
      toValue: -this.transationValue + meter,
      duration: this.props.scrolltime || 5000,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start(() => {
      this.animation = new Animated.Value(0);
      this.initPosition();
      this.startAnimation();
    });
  }

  initPosition() {
    this.key++;
    if (this.key < 2) {
      // React.Children.forEach(this.props.children, (child, index) => {
      //     let props = {
      //         key: `${this.key}${index}`,
      //         ...child.props
      //     };
      //     this.arr.push(React.cloneElement(child, props));
      // });
      React.Children.forEach(this.props.children, (child, index) => {
        let newProps = {
          key: `${this.key}${index}flag`,
          ...child.props,
        };
        this.arr.push(React.cloneElement(child, newProps));
      });
    }

    this.setState({
      newChildren: [...this.arr],
    });
  }

  componentDidMount() {
    this.initPosition();
    this.startAnimation();
  }

  componentWillUnmount() {
    this.startAnimation = () => {};
  }

  render() {
    const {styles, direction} = this.props;
    const {newChildren} = this.state;
    return (
      <View style={{overflow: 'hidden', height: 35, justifyContent: 'center'}}>
        <Animated.View
          style={{
            transform: [
              direction !== 'vertical'
                ? {translateX: this.animation}
                : {translateY: this.animation},
            ],
            flexDirection: 'row',
          }}>
          {newChildren}
        </Animated.View>
      </View>
    );
  }
}

组件可以在React中直接使用,把Animated.View 改成Animated.div即可

猜你喜欢

转载自www.cnblogs.com/it-Ren/p/12049081.html
今日推荐