在尝试制作一个可扩展组件时,当点击时,它会通过动画扩展至动态高度,我遇到了这种奇怪的行为,其中
useRef
对象不会更新。
const contentHeight = useRef(0)
const [expand, setExpand] = useState(false)
const eleHeight = useSharedValue(0)
const animatedStyle = useAnimatedStyle(() => {
console.log(contentHeight.current)
return ({
height: withSpring(eleHeight.value)
})})
return <View>
<TouchableOpacity onPress={()=>setExpand(!expand)}>
<Text>{title}</Text>
<Animated.View
style=[animatedStyle]
onLayout={getContentHeight}
>
{expand && <Text>unknown content</Text> }
</Animated.View>
</TouchableOpacity>
</View>
内部
getContentHeight
:
const getContentHeight = (event) => {
const height = event.nativeEvent.layout.height
console.log('-------onlayout')
if (contentHeight.current === 0) {
console.log('CH is zero now', contentHeight.current, height)
contentHeight.current = height;
eleHeight.value = height
console.log('updated to ', contentHeight.current, height)
}
};
输出始终
console: CH is zero now 0 30
console: updated to 0 30
(大约30,因为有Spring)
当我设置contentHeight.current = height
并且高度不为0时,useRef值没有改变,这很奇怪。
如果有人愿意帮助我的话,我还使用
react-native-reanimated
来努力处理自定义布局动画。
编辑:经过数小时的调试后的一些主要发现和澄清...
我发布的代码不是完整的代码,没有实现我想要的功能,但它确实允许您重新创建问题。
onLayout 受到animatedStyle 的影响!我一开始以为情况正好相反。在初始渲染过程中,onLayout 被调用,高度为 30。实际高度为 0,但因为
eleHeight
从 0 开始,所以 padding 和 margin 各为 15,因此值为 30。(我没有包括这些)代码中的样式)。
我在
contentHeight.current
中使用useAnimatedStyle
导致了它不更新的行为,但我不知道为什么。
我目前面临同样的问题。请问你现在工作了吗?