我是一个反应的初学者-本地人,并希望管理我的android设备的wifi。基本上,我想请求允许打开wifi,显示wifi列表并断开wifi连接,所以我遵循了本教程:
下面是请求许可的代码
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
var wifi = require('react-native-android-wifi');
export default class App extends Component {
wifi.isEnabled((isEnabled) => {
if (isEnabled) {
console.log("wifi service enabled");
} else {
console.log("wifi service is disabled");
}
});
render() {
return (
<View style={styles.container}>
<Text>Welcome to React Native!</Text>
<Text>To get started, edit App.js</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});我发现了一个错误:
有人能帮帮我吗,为什么我会犯这个错误,我该怎么做?
发布于 2018-12-23 16:44:02
这是因为您需要在您的wifi.isEnabled中调用您的componentDidMount,而不是在类的主体中调用。
将组件更新为:
export default class App extends Component{
componentDidMount() {
wifi.isEnabled((isEnabled)=>{
if (isEnabled){
console.log("wifi service enabled");
}else{
console.log("wifi service is disabled");
}
});
}
render() {
return (
<View style={styles.container}>
<Text>Welcome to React Native!</Text>
<Text>To get started, edit App.js</Text>
</View>
);
}
}看看反应-原生-android-wifi的回购,还有几个步骤你还需要做。
首先,您需要请求访问该位置的权限。所以让我们在componentDidMount中这样做,因为这是一个异步请求,我们需要确保您的componentDidMount也是异步的。
第二,我们要进行检查。我们可以把它绑在按钮上。
我们还需要从react-native导入一些东西,因为我们正在使用Button组件,并且希望为Android请求权限。
import { Button, PermissionsAndroid } from 'react-native';
export default class App extends Component {
async componentDidMount () {
this.askForUserPermissions();
}
async askForUserPermissions () {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Wifi networks',
'message': 'We need your permission in order to find wifi networks'
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('Thank you for your permission! :)');
} else {
console.log('You will not able to retrieve wifi available networks list');
}
} catch (err) {
console.warn(err);
}
}
checkWiFi () {
wifi.isEnabled((isEnabled) => {
if (isEnabled) {
console.log('wifi service enabled');
} else{
console.log('wifi service is disabled');
}
});
}
render () {
return (
<View style={styles.container}>
<Button title={'check wifi'} onPress={this.checkWiFi.bind(this)} />
<Text>Welcome to React Native!</Text>
<Text>To get started, edit App.js</Text>
</View>
);
}
}有关如何设置此操作的更多细节,请查看回购中的示例,它们将展示如何完成您可能希望做的大多数事情。
https://stackoverflow.com/questions/53905294
复制相似问题