LayoutAnimation
LayoutAnimation
是在 React Native 中为视图添加动画的一种常用方法。
FlashList 支持 LayoutAnimation
,但您需要在 React Native 的 LayoutAnimation.configureNext
之前调用 prepareForLayoutAnimationRender()
。prepareForLayoutAnimationRender
是一个实例方法,因此您必须通过 ref
属性保留对 FlashList
实例的引用。
// This must be called before `LayoutAnimation.configureNext` in order for the animation to run properly.
listRef.current?.prepareForLayoutAnimationRender();
// After removing the item, we can start the animation.
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
为了使动画正常工作,如果您尚未这样做,还需要向 FlashList
组件添加 keyExtractor
属性。
注意
LayoutAnimation
在 Android 上是实验性的,因此我们不能保证在与 FlashList
一起使用时的稳定性。
示例
import React, { useRef, useState } from "react";
import { View, Text, Pressable, LayoutAnimation } from "react-native";
import { FlashList } from "@shopify/flash-list";
const List = () => {
const [data, setData] = useState([1, 2, 3, 4, 5]);
const list = useRef<FlashList<number> | null>(null);
const removeItem = (item: number) => {
setData(
data.filter((dataItem) => {
return dataItem !== item;
})
);
// This must be called before `LayoutAnimation.configureNext` in order for the animation to run properly.
list.current?.prepareForLayoutAnimationRender();
// After removing the item, we can start the animation.
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
};
const renderItem = ({ item }: { item: number }) => {
return (
<Pressable
onPress={() => {
removeItem(item);
}}
>
<View>
<Text>Cell Id: {item}</Text>
</View>
</Pressable>
);
};
return (
<FlashList
// Saving reference to the `FlashList` instance to later trigger `prepareForLayoutAnimationRender` method.
ref={list}
// This prop is necessary to uniquely identify the elements in the list.
keyExtractor={(item: number) => {
return item.toString();
}}
renderItem={renderItem}
estimatedItemSize={100}
data={data}
/>
);
};
export default List;