1

我正在使用 refs 为 View 设置动画,但是 refs 抛出了一个未定义的错误。但是,如果我注释掉我访问 ref、加载页面、取消注释代码并重新加载页面的尝试,则动画效果很好。

我的代码:

    export const AccountScreen = ({ navigation }) => {
        
          return (
            <SafeAreaView style={{ backgroundColor:'#FFFFFF', flex: 1 }}>
              <Animatable.View style={styles.container} ref={ref => {this.containerRef = ref}}>
              </Animatable.View>
            </SafeAreaView>
          )
      };

   launchOpenAnimation()
   function launchOpenAnimation () {
     this.containerRef.animate(appearContainerAnimation); //If I comment this out, reload, and un-comment, it works
   }

我能做些什么来解决这个问题?似乎在launchOpenAnimation()执行 my 时没有定义 ref ,而是在之后定义了它,因此如果我将其注释掉、重新加载、取消注释并再次重新加载,代码就会工作。

4

1 回答 1

2

首先,您的问题在调用组件和功能组件之间搞砸了,因为this功能组件中没有。我将使用useRef和将它们转换为功能组件useEffect

在第一次运行时 this.containerRef 尚未分配给 ref Animatable

尝试这个

export const AccountScreen = ({ navigation }) => { 
  const animateRef = useRef()
  useEffect(() =>{
     launchOpenAnimation()
     function launchOpenAnimation () {
       // add ? to make sure animate is called only when this.containerRef exists
     containerRef?.current.animate(appearContainerAnimation);
}    
  },[])
      
  return (
    <SafeAreaView style={{ backgroundColor:'#FFFFFF', flex: 1 }}>
      <Animatable.View style={styles.container} ref={ref => {
            ref.animate(appearContainerAnimation); // add this if you need to run when initial render run
            animateRef.current = ref
            }}>
      </Animatable.View>
    </SafeAreaView>
  )
};

于 2020-07-04T09:43:34.873 回答