wants to autoscroll flatlist in react native

2020-07-26 11:03发布

问题:

I am trying to auto scroll my flatlist but when I run my code I cannot scroll auto and if I want to manual scroll it comes to index 0 after every 5 seconds .. here is my all code of flat list and its refs function

in constructor

this.flatList1=null;

And in componentwillMount

componentWillMount(){

  setInterval(()=>{
    if(this.flatList1!==null){
      this.flatList1.scrollToOffset({ offset: 1 })
    }
  }, 5000);
}

<FlatList horizontal
  data={this.state.getallvideos}
  ref={flatList1 => { this.flatList1 = flatList1 }}
  renderItem={({item}) =>  

    <TouchableOpacity onPress={this.playvideoinnetpage.bind(this,item.vd_link,item.vd_thumbnail,item.vd_id,item.vd_title)}>

      <Card
        containerStyle={{
          padding:0, 
          width:180,
          height:112,
          backgroundColor:'#000',
          borderColor:'#000',
          marginTop:10,
          marginLeft: 5,
          marginRight:5,
          marginBottom:5
        }}
        image={{uri:item.vd_thumbnail}}
        imageStyle={'stretch'}
      >

        <View style={{position:'relative',bottom:75,}}> 
          <Text numberOfLines={1} style={{color:'#fff',fontWeight:'bold',fontSize:14}}> {item.vd_title}</Text>
        </View>
      </Card>
    </TouchableOpacity>
  }
/>

回答1:

You can read the answer here [ How do I make a list (FlatList) automatically scroll through the elements using Animated? ]

scrollToIndex = (index, animated) => {
   this.listRef && this.listRef.scrollToIndex({ index, animated })
 }

 componentDidMount() {  // use componentDidMount instead since the WillMount is getting deprecated soon
   setInterval(function() {
     const { sliderIndex, maxSlider } = this.state
     let nextIndex = 0

     if (sliderIndex < maxSlider) {
       nextIndex = sliderIndex + 1
     }

     this.scrollToIndex(nextIndex, true)
     this.setState({sliderIndex: nextIndex})
   }.bind(this), 3000)
 }

You should essentially increment the index instead of setting it to 1 every 5000ms like in above code. Keep the currentIndex, maxIndex and use the scrollToIndex function after incrementing currentIndex like above. Do make sure you are modifying the state after updating the currentIndex using setInterval