ScrolltoIndex不起作用,对flatlist进行本地反应



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

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

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

react native: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>

尝试添加对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});
};

尝试以下操作:

<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});
};

一个对我有效的修复程序是删除contentContainerStyle道具上的flex:1

任何使用useRef钩子的基于函数的组件的人,都可以这样做。

function MyComponent() {
const myListRef = useRef(null);
const goIndex = (index) => {
myListRef.current.scrollToIndex({index});
};
return (
<FlatList
ref={ref => myListRef.current = ref}
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>
}
/>
);
}

这个答案重申了上面其他人的回答,但对基于函数的组件进行了简化。

最新更新