How do you animate the height in react native when you don't know the size of the content?

后端 未结 4 1876
逝去的感伤
逝去的感伤 2021-01-03 17:16

In react-native, how do you animate the size of a View when you dont know the size of it\'s contents?

Let\'s say the View\'s content height can be

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 18:07

    The method I've taken is to spend layout passes getting the height of the "truncated" component and the height of the "full size" component (you need a way for the truncated height to be deterministic, usually by knowing how to render a "row" of content). Essentially before you have those values, you render these as two separate views that are hidden:

    hidden: {
      position: 'absolute',
      left: 0,
      top: 0,
      opacity: 0,
    },
    

    Use onLayout to capture their heights:

    const onLayoutTruncated = ({nativeEvent}: LayoutChangeEvent) => {
      if (!doneProcessing) {
        truncatedHeight = nativeEvent.layout.height;
        checkIfDoneProcessingLayout();
      }
    };
    
    const onLayoutFull = ({nativeEvent}: LayoutChangeEvent) => {
      if (!doneProcessing) {
        fullHeight = nativeEvent.layout.height;
        checkIfDoneProcessingLayout();
      }
    };
    

    checkIfDoneProcessingLayout() will check if both truncatedHeight and fullHeight are set, and make a state change if they both are (doneProcessing = true).

    From there you should unhide the truncated view and be able to animate between both height values using an Animated.Value and interpolation:

    const expandingHeight = animatedValue.interpolate({
      inputRange: [0, 1],
      outputRange: [truncatedHeight, fullHeight],
    });
    

    Trigger the expanding/collapsing animation on click using Animated.timing

    Animated.timing(animatedValue, {toValue: isExpanded ? 0 : 1, easing: SOME_EASING_FUNCTION, duration: SOME_DURATION}).start();
    

提交回复
热议问题