首页 > 解决方案 > 离开应用程序时 React Native 停止动画

问题描述

我有一个Animated.timing并且我想在用户导航到另一个应用程序时停止它,这可能吗?

标签: react-nativeanimation

解决方案


你可以AppState这样使用:

import React, {Component} from "react"
import {AppState, View} from "react-native"

class YourClass extends Component {
    state = {
       appState: AppState.currentState
    }
    componentDidMount() {
      //add a listener here
      AppState.addEventListener("change", this._handleAppStateChange);
    }

    componentWillUnmount() {
          // remember add this line
      AppState.removeEventListener("change", this._handleAppStateChange);
    }

    _handleAppStateChange = (nextAppState) => {
           if (this.state.appState.match(/inactive|background/) && nextAppState === "active"){
           console.log("App has come to the foreground!")

           }else{
             //here you can call stop animation function
           }
           this.setState({appState: nextAppState});
     }


     render() {
        return (
        <Text>Current state is: {this.state.appState}</Text>
        );
     }

}

推荐阅读