gpt4 book ai didi

react-native - 在 React Native 的功能组件中获取可变子组件的高度

转载 作者:行者123 更新时间:2023-12-05 07:14:59 25 4
gpt4 key购买 nike

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

这是卡片组件 Not expanded card component

与 child 展开 enter image description here

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

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

处理布局

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

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

我希望动画能够灵活地扩展到 children 的高度。

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

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

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

最佳答案

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

关于react-native - 在 React Native 的功能组件中获取可变子组件的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59755617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com