React-native: FlatList get refs to scroll

隐身守侯 提交于 2019-12-10 17:54:40

问题


I'm currently building an app with react native:

this is my flatlist:

    <FlatList
      ref={"myFlatList"}
      data={data}
      keyExtractor={this._keyExtractor}
      renderItem={this._renderItem}
    />

In this function I want to scroll to a specific index:

  _enableTVEventHandler() {
    this._tvEventHandler = new TVEventHandler();
    this._tvEventHandler.enable(this, function(cmp, evt) {
        this.refs["myFlatList"].scrollToIndex({viewPosition: 0.5, index: 2});
    }.bind(this));
  }

But I have an error: Cannot read property 'scrollToIndex' of undefined


回答1:


Two things that I can see,

  1. You need not define string refs within {}. However React docs suggest you to make use of ref callback

Do it something like

 <FlatList
      ref={(list) => this.myFlatList = list}
      data={data}
      keyExtractor={this._keyExtractor}
      renderItem={this._renderItem}
    />
  1. You need to bind your function to be able to refer to the correct context

Do it like

_enableTVEventHandler = () => {
    this._tvEventHandler = new TVEventHandler();
    this._tvEventHandler.enable(this, function(cmp, evt) {
        this.myFlatList.scrollToIndex({viewPosition: 0.5, index: 2});
    }.bind(this));
  }

or

constructor(props) {
    super(props) ;
    this._enableTVEventHandler = this._enableTVEventHandler.bind(this); 
}


来源:https://stackoverflow.com/questions/43936486/react-native-flatlist-get-refs-to-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!