当儿童身高动画时,React Native View onLayout重新渲染每帧

时间:2019-11-06 11:06:15

标签: react-native animation layout layout-animation usecallback

要使用View创建自定义translateY,我必须使用onLayout计算容器和内容的高度。这很好用,但是今天我添加了一个动画的Accordion组件。碰巧会触发onLayout函数在每个计算的帧上渲染,这使我的应用程序非常慢。我尝试添加useCallbackLayoutAnimation来解决此问题,但这似乎都没有用。

有没有一种方法只能在动画前后触发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>
  );
});

0 个答案:

没有答案