joh*_*nny 2 android ios react-native react-native-maps
我有与谷歌一起运行的 IOS 和 Android 的 react-native 地图。有没有办法mapType
在 react-native expo 应用程序中启用像谷歌地图应用程序那样的图层切换器?以便用户可以切换地图类型(标准、卫星、....)
代码的简化版本
constructor(props) {
super(props);
this.state = {
mapRegion: null,
markers: [],
mapType: null
};
}
switchMapType() {
console.log('Changing');
this.state.mapType = 'satellite'
}
render() {
return (
<MapView
provider="google"
mapType={this.state.mapType}
>
<Icon
onPress={this.switchMapType}
/>
</MapView>
);
}
Run Code Online (Sandbox Code Playgroud)
在state 内部时出现未定义错误switchMapType()
。
查看文档可以像将正确的样式传递给mapType
道具一样简单
https://github.com/react-native-community/react-native-maps/blob/master/docs/mapview.md
要显示的地图类型。
您收到该错误是因为可能需要绑定您的函数,以便它知道this
要使用的值。您可以通过将以下内容放入构造函数中来在构造函数中执行此操作
constructor(props) {
...
this.switchMapType = this.switchMapType.bind(this);
...
}
Run Code Online (Sandbox Code Playgroud)
或者您可以switchMapType
通过将其声明更改为箭头函数来转换为
switchMapType = () => {
...
}
Run Code Online (Sandbox Code Playgroud)
或者你可以在调用它时绑定函数
<Icon
onPress={this.switchMapType.bind(this}
/>
Run Code Online (Sandbox Code Playgroud)
您可以查看这篇文章了解更多详情https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
我更喜欢自己使用箭头函数。
我还注意到您的函数中存在一个错误,即您switchMapType
设置状态的方式。你在呼唤this.state.mapType = 'satellite'
你应该不能操纵的状态是这样的。像这样改变状态不会强制重新渲染(这是你想要的),它可能会导致意想不到的后果。有关设置状态的更多信息,请参阅本文https://medium.com/@baphemot/understanding-reactjs-setstate-a4640451865b
如果你想改变你应该使用的状态 this.setState({ key1: value1, key2, value2 });
因此,如果您将switchMapType
函数更新为以下内容,则它应该可以工作
switchMapType = () => {
console.log('changing');
this.setState({ mapType: 'satellite' });
}
Run Code Online (Sandbox Code Playgroud)
如果您希望能够在satellite
和standard
版本之间切换,您可以执行以下操作。这使用三元语句来处理if/else
https://codeburst.io/javascript-the-conditional-ternary-operator-explained-cac7218beeff
switchMapType = () => {
console.log('changing');
this.setState({ mapType: this.state.mapType === 'satellite' ? 'standard' : 'satellite' });
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5367 次 |
最近记录: |