useRef挂钩不适用于lottie-react-native

时间:2019-10-08 09:41:47

标签: react-native react-hooks

我已经将class component的钩子升级为functional component的钩子,但是现在裁判不起作用。

之前:

class A extends Component{

   animation = null;

   onPress = ()=> {
      this.animation.play();
   }

   render(){
     return (
        <View>
          <LottieView
            source={require('./file.json')}
            ref={animation => {this.animation = animation}}
          />
          <Button onPress={this.onPress} title='click me' />
        </View>
     );
   }
}

属于类Component以上代码效果很好。

但是我升级以下代码不起作用。

更新的代码:

const A = props => {

   const animation = useRef(null);

   const onPress = ()=> {
      animation.play();
   }

   return (
        <View>
          <LottieView
            source={require('./file.json')}
            ref={animation}
          />
          <Button onPress={onPress} title='click me' />
        </View>
   );
}

1 个答案:

答案 0 :(得分:2)

您缺少.current

请参见工作示例,网址为:https://snack.expo.io/@zvona/lottie-and-useref-example

const onPress = () => {
  animation.current.play();
}