如何使用FlatList自动滚动?

时间:2018-04-26 14:27:28

标签: react-native react-native-flatlist

以下是我尝试使用setInterval函数来设置变量content每秒都会更改,我发现onMomentumScrollEnd可以在滚动时获取位置y FlatList

然后我被卡住了,我event.nativeEvent.contentOffset.y = this.state.content;可以让FlatList自动滚动。显然不是。

任何人都可以给我一些建议吗?提前谢谢。

我的数据来自API 这是我的App.js:

import React from 'react';
import { View, Image, FlatList, Dimensions } from 'react-native';

const { width, height } = Dimensions.get('window');
const equalWidth = (width / 2 );

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.renderRow = this.renderRow.bind(this);
    this.state = { movies: [], content: 0 };
  }

  componentWillMount() {
    fetch('https://obscure-reaches-65656.herokuapp.com/api?city=Taipei&theater=Centuryasia')
      .then(response => response.json())
      .then(responseData => {
        console.log(responseData);
        this.setState({ movies: responseData[0].movie });
      })
      .catch((error) => console.log(error));

      this.timer = setInterval(() => {
          this.setState({content: this.state.content+1 })
      }, 1000);
  }
  // get the jsonData key is item and set the value name is movie
  renderRow({ item: movie }) {
    console.log('renderRow => ');
    return (
      <View>
        <Image source={{ uri: movie.photoHref}} style={{ height: 220, width: equalWidth }} resizeMode="cover"/>
      </View>
    );
  }

  render() {
    const movies = this.state.movies;
    // it well be rendered every second from setInterval function setState
    console.log('render');
    return (
      <View style={{ flex: 1 }}>
        <FlatList
          data={movies}
          renderItem={this.renderRow}
          horizontal={false}
          keyExtractor={(item, index) => index}
          numColumns={2}
          onMomentumScrollEnd={(event) => {
            console.log(event.nativeEvent.contentOffset.y);
            event.nativeEvent.contentOffset.y = this.state.content;
          }}
        />
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

您需要告诉您的FlatList您希望它使用scrollToOffset()滚动到新位置。

通过添加道具,在班级中存储对FlatList的引用 ref={flatList => { this.flatList = flatList }}到它。

然后,调用this.flatList.scrollToOffset({ offset: yourNewOffset })滚动到所需的偏移量。

此方法的文档为here