Tot*_*ndo 5 react-native react-native-flatlist
我正在尝试在平面列表中实现类似“onBeginReached”的道具。我想以对用户透明的方式在数据数组的开头附加一些数据。
所以使用这个 flatList :
const App = () => {
const flatListRef = useRef(null);
const [data, setData] = useState(generateData(20));
const renderItem = ({ item }) => {
console.log(item);
return (
<View style={styles.itemContainer}>
<Text style={styles.itemText}>{item}</Text>
</View>
);
};
const handleMomentumScroll = (event) => {
console.log("Momentum end")
const xOffset = event.nativeEvent.contentOffset.x;
const index = Math.round(xOffset / 30);
if (index < 1) {
setData([-10 ,-9, -8, -7, -6,-5, -3, -2, -1, ...data]);
}
};
return (
<FlatList
style={{ width: 200, alignSelf: 'center', marginTop: 150 }}
initialScrollIndex={10}
horizontal
data={data}
snapToAlignment={'start'}
decelerationRate={'fast'}
snapToInterval={30}
getItemLayout={(data, index) => ({
length: 30,
offset: 30 * index,
index,
})}
keyExtractor={(item, index) => index.toString()}
renderItem={renderItem}
onMomentumScrollEnd={handleMomentumScroll}
/>
);
};
const styles = StyleSheet.create({
itemContainer: {
alignItems: 'center',
justifyContent: 'center',
width: 30,
height: 30,
borderRadius: 15,
backgroundColor: 'blue',
},
itemText: {
color: 'white',
},
});
Run Code Online (Sandbox Code Playgroud)
(https://snack.expo.io/GUblotbZc)
如果我滚动到索引 0,它会将我的新数据取消移动到我的数据数组。但是,它会自动滚动到新数据数组的第一个索引。我想在将新数据移至数组时保留当前位置。
有办法实现这种行为吗?
这是演示:https: //snack.expo.io/@nomi9995/flatlisttest
在 IOS 中使用maintainVisibleContentPosition props 来防止自动滚动,但不幸的是,它在 Android 上不起作用,但好消息是Android 已收到拉取请求,需要与 React Native 合并。
<FlatList
ref={(ref) => { this.chatFlatList = ref; }}
style={styles.flatList}
data={this.state.items}
renderItem={this._renderItem}
maintainVisibleContentPosition={{
minIndexForVisible: 0,
}}
/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3079 次 |
| 最近记录: |