美文网首页
ReactNative实现一个无限自动轮播

ReactNative实现一个无限自动轮播

作者: 呦释原点 | 来源:发表于2020-01-15 16:09 被阅读0次

逻辑
单方向运动 01--->1--->2--->3--->02 >> 01
01和02是相同的两个页面

从1一直滚动3, 3滚动到02, 此滚动结束后瞬间跳转到01,当前页码切换到第0页。然后走定时方法从第零页向第一页滚动 从01滚动到1, 然后继续向下滚动

代码

import React from 'react';
import {
  View,
  Text,
  StatusBar,
  StyleSheet,
  ScrollView,
  Dimensions,
} from 'react-native';


export default class Advertisement extends React.Component {

  constructor(props) {
    super(props)
    this.state={
      currentPage:0,
      ads:["0", "1", "2", "3","0"]
    }
  }

  _startTimer = ()=>{
    this.interval = setInterval(() => {
      let np = this.state.currentPage + 1;
      let nextPage = np > (this.state.ads.length -1) ? 0 : np;
      this.setState({
        currentPage: nextPage
      })

      let sW = Dimensions.get("screen").width
      let offsetX = sW * this.state.currentPage;

      this.refs["scrollView"].scrollTo({x:offsetX, y:0, animated:true})

    }, 1000);

  }

  _endTimer = ()=>{
    this.timer && clearTimeout(this.timer);
    this.interval && clearInterval(this.interval);
  }
  scrollEnd = ()=>{
    if(this.state.currentPage == this.state.ads.length-1 ){
      this.setState({
        currentPage : 0
      })
      this.refs.scrollView.scrollTo({x:0, y:0, animated:false})
    }
  }


  componentDidMount(){
    this._startTimer();
  }

  componentWillUnmount(){
    this._endTimer();
  }

  render(){
    return(
      <View style={styles.ad}>
        <ScrollView horizontal={true}
        pagingEnabled={true}
        showsHorizontalScrollIndicator={false}
        bounces={false}
        ref="scrollView"
        onMomentumScrollEnd={this.scrollEnd}
        >
          <View style={[styles.adItem, {backgroundColor:"red"}]}><Text>0</Text></View>
          <View style={[styles.adItem, {backgroundColor:"blue"}]}><Text>1</Text></View>
          <View style={[styles.adItem, {backgroundColor:"cyan"}]}><Text>2</Text></View>
          <View style={[styles.adItem, {backgroundColor:"yellow"}]}><Text>3</Text></View>
          <View style={[styles.adItem, {backgroundColor:"red"}]}><Text>0</Text></View>
        
        </ScrollView>
      </View>        

    )
  }
}


const styles = StyleSheet.create({
  ad:{
    height: 200,
    backgroundColor: 'lightgray',
    marginTop: 10,
  },
  adItem:{
    width:Dimensions.get('screen').width,
    height:200,
  }
});

双向
如果双向 逻辑变为
3 <-> 0 <-> 1 <-> 2 <-> 3 -> 0

-> 方向:从后0结束瞬间跳转到前0
<- 方向:从前3结束瞬间跳转到后3

后记:
这是很早很早自己搞轮播图时的逻辑了。在实际开发中类似这种功能一直使用的别人封装好的库。(想说有现成的东西就不想自己再搞一个了,而且自己搞的还不一定好用。 别人的需求满足不了时改改他的就行了。)
React、ReactNative从火到火到大厂放弃到现在。 各种原因现在才了解一点,说晚也不算晚。
时间富裕学点东西总是好的。学的多了会知道表皮的东西是相通的,深层的东西往往需要时间沉淀。
感觉有点浮躁,那就浮躁的学,啥时候不浮躁了就沉淀。
等ReactNative不想学了就去搞Flutter😂😂😂😂

相关文章

网友评论

      本文标题:ReactNative实现一个无限自动轮播

      本文链接:https://www.haomeiwen.com/subject/qrvtzctx.html