条件组件呈现反应本机



我正在尝试呈现条件组件。我有一个带有位置的MapView,我想实现的是:如果位置是用户授予的,或者找不到位置,我想呈现一个用户可以手动键入位置的Textinput,而不是MapView。这是我的代码

export default class GpsLocation extends React.Component {
constructor(props) {
super(props);
this.state = {
region: null,
};
this._getLocationAsync();
}
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
let location = await Location.getCurrentPositionAsync({
enableHighAccuracy: true,
});
let region = {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
latitudeDelta: 0.0045,
longitudeDelta: 0.0045,
};
this.setState({ region: region });
};
render() {
if (this.status === "granted") {
return (
<View style={styles.locationContainer}>
<Text style={styles.note}>Adresa</Text>
<MapView
initialRegion={this.state.region}
showUserLocation={true}
showCompass={true}
rotateEnabled={false}
style={{ flex: 1, borderRadius: 10 }}
></MapView>
</View>
);
} else {
return (
<TextInput/>
);
}
}
}

尝试这种方式

constructor(props) {
super(props);
this.state = {
region: null,
status : undefined, // add initially `undefined`
};
this._getLocationAsync();
}
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
.......
this.setState({ ... , status }); // update status here
};
render() {
// change here also
return this.state.status === "granted" ? (
<View style={styles.locationContainer}>
<Text style={styles.note}>Adresa</Text>
<MapView
initialRegion={this.state.region}
showUserLocation={true}
showCompass={true}
rotateEnabled={false}
style={{ flex: 1, borderRadius: 10 }}
></MapView>
</View>
) : <TextInput/> ;       
}

最新更新