0

我想使用本机模块在 react-native 中使用服务,如果 Wifi 连接从关闭更改为打开,只需显示连接更改的 toast

4

1 回答 1

0

您可以使用react-native-netinfo插件。安装此插件,然后将以下代码添加到您的文件中:

import NetInfo from '@react-native-community/netinfo';
...
...

class App extends Component {
    netInfoHandler;
    constructor(props) {
        super(props);
        this.state = {
            isConnected: true
        }
    }

    componentDidMount = () => {
        this.netInfoHandler = NetInfo.addEventListener(async (state) => {
            if (this.state.isConnected !== state.isConnected) {
                this.setState({ isConnected: state.isConnected });
                // show toast here
            }
        });
    }

    componentWillUnmount = () => {
        this.netInfoHandler();
    }

    render() {
        return (
            ...
            // your view
        )
    }
}

export default App
于 2019-10-08T11:51:44.380 回答