无限自动循环的消息滚动组件

大概的思路:数组的前后各加一个数据,例如原来的数组是[1,2,3,4,5], 前后加数据变成:[5,1,2,3,4,5,1]。首次加载滚动组件,初始化到索引1的位置,一直:索引+1,到最后一个的时候,滚到索引为1的位置。
具体代码如下:

/**
 * 消息提醒
 */
export class MarqueeView extends React.Component {

  scrollViewRef = React.createRef();
  scrollHeight = 0;

  constructor(props) {
    super(props)

    let list = props.dataList ?? [];
    if (list.length > 1) {//实现无限循环的效果,[5,1,2,3,4,5,1]
      list = [list[list.length - 1], ...list, list[0]];
    }

    this.state = {
      pageIndex: 1,//索引从1开始
      dataList: list,
    }
    this.itemHeight = props.itemHeight ?? 48
    this.scrollHeight = this.state.dataList.length * (this.itemHeight)
  }

  componentDidMount() {
    if (this.state.dataList.length > 1) {//初始化,跳转到"1"的位置
      this.scrollToIndex(this.state.pageIndex, false);
    }

    if (this.props.navigation) {
      this._unFocusSubscribe = this.props.navigation.addListener('focus', () => {
        if (this.state.dataList.length > 1) {
          this.loopStart()
        }
      });
      this._unBlursubscribe = this.props.navigation.addListener('blur', () => {
        this.timeId && clearTimeout(this.timeId);
      });
    } else {
      if (this.state.dataList.length > 1) {
        this.loopStart()
      }
    }
  }

  componentWillUnmount() {
    this.timeId && clearTimeout(this.timeId)
    this._unFocusSubscribe && this._unFocusSubscribe();
    this._unBlursubscribe && this._unBlursubscribe();
  }

  //更新数据
  updateMsgList = (list) => {
    let realList = [];
    if (list.length > 1) {
      realList = [list[list.length - 1], ...list, list[0]];
    } else {
      realList = list;
    }

    this.scrollHeight = realList.length * this.itemHeight;
    this.setState({ dataList: realList });

    this.timeId && clearTimeout(this.timeId)
    if (realList.length > 1) {
      if (this.state.dataList.length > 1) {//初始化,跳转到"1"的位置
        this.scrollToIndex(this.state.pageIndex, false);
      }  
      this.loopStart()
    }
  }

  scrollToIndex = (pageIndex, animated) => {
    const y = pageIndex * this.itemHeight;
    if (this.scrollViewRef?.current) {
      this.scrollViewRef?.current.scrollTo({ y, animated });
    }
  }


  loopStart = () => {
    this.timeId && clearTimeout(this.timeId)

    this.timeId = setTimeout(() => {
      const { pageIndex, dataList } = this.state;
      let newIndex = pageIndex;
      let animated = true;

      if (pageIndex >= dataList.length - 1) {//倒数最后一个的话,就跳到第二个(实际是1的位置)
        newIndex = 1;
        animated = false;
      } else {
        newIndex = pageIndex + 1;
      }

      this.scrollToIndex(newIndex, animated);
      this.setState({ pageIndex: newIndex })

      this.loopStart();

    }, 2000)
  }

  render() {
    const { dataList } = this.state;
    const { style, imageStyle, imageTintColor, textStyle, hideImage = false } = this.props;
    if (dataList.length <= 0) {
      return <View />;
    } else {
      return <View style={[{
        flexDirection: 'row',
        backgroundColor: 'rgba(0, 0, 0, 0.80)',
        alignItems: 'center'
      }, style]}>
        <Image source={require("@assets/my/team/message_notify.png")}
          style={[{ width: 20, height: 20, marginHorizontal: 12 }, imageStyle]}
          tintColor={imageTintColor} />
        <ScrollView
          horizontal={false}
          ref={this.scrollViewRef}
          style={{ flex: 1, maxHeight: this.itemHeight }}
          pagingEnabled={true}
          scrollEnabled={true}
          showsVerticalScrollIndicator={false}>
          {dataList.map((item, index) => {
            return <UIButton key={index}
              style={{
                height: this.itemHeight,
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
              }}
              onPress={() => item.action && item.action()}>

              <View style={{ flex: 1 }}>
                <Text style={[{ color: '#fff', fontSize: 12 }, textStyle]}>{item.title}{"  索引:" + (index)}</Text>
              </View>
              {hideImage ? null : <Image source={require("@assets/my/right_arrow_big.png")}
                style={{ width: 16, height: 16, marginHorizontal: 12, tintColor: imageTintColor }}
                tintColor={imageTintColor} />}
            </UIButton>
          })}
        </ScrollView>
      </View>
    }

  }
}

使用该组件:

<MarqueeView
         dataList={[
           { title: "这是第一个消息", action: () => { } },
           { title: "这是第二个消息", action: () => { } },
           { title: "这是第三个消息", action: () => { } },
           { title: "这是第四个消息", action: () => { } },
           { title: "这是第五个消息", action: () => { } },
         ]} />
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容