作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图在我的组件中获取子项的高度以实现动画。
我想获取子组件的高度,以便为高度值设置动画以实现动画扩展。
{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/
我是一名优秀的程序员,十分优秀!