首页 > 解决方案 > React-Native :使用 componentDidMount 上的 ref 计算 FlatList 的 scrollToItem 并渲染它

问题描述

我有一个 FlatList 可以呈现 1-10 的数字以及一个单选按钮。如果我预先选择了可能是动态的数字,则该编号的单选按钮是预先选择的。在这种情况下如何计算scrollToItem/scrollToIndex?

componentDidMount() {
     this.scrollToItem();
}

 scrollToItem = () => {
    let dynamicIndex = dynamicIndex 
  //calcuate the dynamic Index

   this.flatListRef.scrollToIndex({ animated: true, index: dynamicIndex });

};

 <FlatList
    ref={ref => {this.flatListRef = ref;}}
    bounces={false}
    keyExtractor={item => item.id}
    data={listData}
    renderItem={({ item, index })=>
       this.renderItem(item,index)}
   />

但它会抛出错误“无法读取索引的属性'scrollToIndex'。基本上它在组件安装期间找不到'this.flatListRef'。

标签: react-nativereact-native-flatlist

解决方案


推荐阅读