要使用View
创建自定义translateY
,我必须使用onLayout
计算容器和内容的高度。这很好用,但是今天我添加了一个动画的Accordion
组件。碰巧会触发onLayout
函数在每个计算的帧上渲染,这使我的应用程序非常慢。我尝试添加useCallback
和LayoutAnimation
来解决此问题,但这似乎都没有用。
有没有一种方法只能在动画前后触发onLayout
?我曾考虑过为onLayout
添加去抖,但希望有另一种解决方案。
export default memo(({ translateY }) => {
const [containerHeight, setContainerHeight] = useState(0);
const [contentHeight, setContentHeight] = useState(0);
console.log('render', containerHeight, contentHeight);
const onLayoutContainer = useCallback(event => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
const height = event.nativeEvent.layout.height;
setContainerHeight(height);
}, []);
const onLayoutContent = useCallback(event => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
const height = event.nativeEvent.layout.height;
setContentHeight(height);
}, []);
return (
<View onLayout={onLayoutContainer}>
<Animated.View
onLayout={onLayoutContent}
style={{ transform: [{ translateY }] }}
>
<Accordion />
<Accordion />
<Accordion />
<Accordion />
<Accordion />
<Accordion />
</Animated.View>
</View>
);
});