【问题标题】:Get height of variable children in a functional component in React Native获取 React Native 中功能组件中可变子项的高度
【发布时间】:2020-01-15 16:23:05
【问题描述】:

我正在尝试获取组件中子项的高度以实现动画。

这是卡片组件

与孩子一起扩展

我想获取子组件的高度,以便为高度值设置动画以实现动画扩展。

{expanded ? (
        <>
          <Animated.View style={{height: someAnimatedHeight}}>
            <View onLayout={handleLayout}>
              {children}
            </View>
          </Animated.View>
          <PromoCodeArea />
        </>
      ) : (
        <PromoCodeArea />
      )}

句柄布局

const handleLayout = ({ nativeEvent }) => {
    setContainerHeight(nativeEvent.layout.height);
  };

但是,handleLayout 在卡片展开之前不会提供高度。我可以让动画使用硬编码的大小。

我希望动画灵活并扩展到孩子的高度。

handleLayout未展开时返回值为0,因此我无法设置toValue

const startAnimation = () => {
    Animated.spring(heightAnimation, {
      toValue: 125, <-- like this to be based on the height of children
    }).start();
  };

我还没有找到使用功能组件和钩子实现这一点的示例。

【问题讨论】:

    标签: react-native react-hooks react-animated


    【解决方案1】:

    一种策略(不漂亮但对我有用)是最初将子样式设置为不透明度 0(所以没有人看到它)并定位“绝对”,这样它就不会干扰您的可见布局和不要将高度设置为 0,以便它以所需的大小呈现。渲染后(考虑使用 useLayoutEffect)从 onLayout 获取高度并保存 - 然后在任何人有机会与之交互之前将样式设置回您当前的样式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 2020-05-30
      • 2022-01-14
      • 2020-11-18
      • 1970-01-01
      • 2021-11-10
      相关资源
      最近更新 更多