useRef.current 由于在 useAnimatedStyle 中访问而无法在 onLayout 回调中工作

问题描述 投票:0回答:1

在尝试制作一个可扩展组件时,当点击时,它会通过动画扩展至动态高度,我遇到了这种奇怪的行为,其中

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
来努力处理自定义布局动画。

编辑:经过数小时的调试后的一些主要发现和澄清...

  1. 我发布的代码不是完整的代码,没有实现我想要的功能,但它确实允许您重新创建问题。

  2. onLayout 受到animatedStyle 的影响!我一开始以为情况正好相反。在初始渲染过程中,onLayout 被调用,高度为 30。实际高度为 0,但因为

    eleHeight
    从 0 开始,所以 padding 和 margin 各为 15,因此值为 30。(我没有包括这些)代码中的样式)。

  3. 我在

    contentHeight.current
    中使用
    useAnimatedStyle
    导致了它不更新的行为,但我不知道为什么。

reactjs react-native animation layout react-native-reanimated
1个回答
0
投票

我目前面临同样的问题。请问你现在工作了吗?

© www.soinside.com 2019 - 2024. All rights reserved.