首页 > 解决方案 > 如何从定制的 flatlist 组件访问 flatList 方法,例如 scrollToIndex?

问题描述

List从 react-native flatList 组件创建了一个自定义组件。现在我想scrollToIndex使用 ref 使用 flatlist 组件的方法,以便我可以通过按自定义按钮滚动到列表顶部。但是当我创建自定义组件时,scrollToIndex 方法似乎不可用。如何使这项工作?

标签: react-native

解决方案


你可以通过道具传递下去

您的自定义组件“列表”文件:

const List = (props) => {
  return (
    <Flatlist
      ref={(ref) => { this.listRef = ref; }}
      initialScrollIndex={this.props.initialScrollIndex}
    />
  );
};

正在使用:

scrollToIndex = () => {
this.listRef.scrollToIndex({animated: true, index: whateverIndex});
}

<List
  initialScrollIndex={whateverIndex}
/>

推荐阅读