ScrolltoIndex在平面列表上无法正常工作

时间:2018-07-25 09:01:31

标签: list react-native scroll react-native-flatlist

我正在使用flatList来渲染json文件中的项目,我想在按下按钮时滚动到特定的索引,我声明了按下按钮的功能,如下所示

goIndex = () => {
    this.flatListRef.scrollToIndex({animated: true,index:5});
};

尽管它没有显示任何错误,但是列表没有移动到指定的索引。

  

反应性:0.55.4

FlatList的附加代码。

<View>
    <FlatList   
        getItemLayout={(data, index) => { return {length: 33, index, offset: 33 * index} }}
        ItemSeparatorComponent={ () => <View style={ { width:"100%", height: .7, backgroundColor: 'rgba( 52,52,52,1)' } } /> }
        data={this.state.outverse}
        renderItem={({item,index}) =>
            <View style={styles2.flatview}>
                <Text style={styles2.name}>{++index}  {item} </Text>
            </View>
        }
    />
</View>

2 个答案:

答案 0 :(得分:4)

尝试添加对您的FlatList组件的引用,如下所示:

<View>
    <FlatList   
        getItemLayout={(data, index) => { return {length: 33, index, offset: 33 * index} }}
        ItemSeparatorComponent={ () => <View style={ { width:"100%", height: .7, backgroundColor: 'rgba( 52,52,52,1)' } } /> }
        data={this.state.outverse}
        ref={(ref) => { this.flatListRef = ref; }}
        renderItem={({item,index}) =>
            <View style={styles2.flatview}>
                <Text style={styles2.name}>{++index}  {item} </Text>
            </View>
        }
    />
</View>

goIndex函数中:

goIndex = () => {
    this.refs.flatListRef.scrollToIndex({animated: true,index:5});
};

答案 1 :(得分:0)

尝试以下操作:

<FlatList
        style={{
          marginLeft: 50,
          paddingTop: 0,
          paddingRight: 0
        }}
        ref={ref => {
          this.flatList_Ref = ref;  // <------ ADD Ref for the Flatlist 
        }}
        removeClippedSubviews={false}
        enableEmptySections={false}
        data={this.props.list}
        keyExtractor={this._keyExtractor}
        renderItem={this._renderItem1}
        ItemSeparatorComponent={this._renderSeparator}

      />

然后调用goIndex函数:

goIndex = () => {

 this.flatList_Ref.scrollToIndex({animated: true,index:5});

};