我找到了两种方法来做到这一点。
很可能第一个是最佳选择:
1.将您需要的有关标记的信息作为第二个参数传递给 _onMarkerPress 的绑定,如下所示:
render() {
return (
<View>
<Text>MySupaFancyMap</Text>
<MapView
style={styles.map}
region={this.state.region}
onRegionChangeComplete={this._onRegionChangeComplete.bind(this)}
>
<MapView.Marker
coordinate={this.state.marker.latlng}
title={this.state.marker.title}
description={this.state.marker.description}
onPress={this._onMarkerPress.bind(this, this.state.marker)}
/>
</MapView>
</View>
);
}
_onMarkerPress (markerData) {
alert(JSON.stringify(markerData));
}
在我的例子中 this.state.marker 是一个像这样的对象:
{
latlng: {
latitude: REGION.latitude,
longitude: REGION.longitude
},
title:'MyHouse',
weather: '26 Celsius'
}
2。从事件信息中提取您需要的信息,如下所示:
<MapView>
//codes here
onPress={this._onMarkerPress.bind(this)}
>
<MapView.Marker
coordinate={this.state.marker.latlng}
/>
<MapView>
并与:
_onMarkerPress (mkr) {
console.warn(mkr.nativeEvent.coordinate);
}
我肯定会选择第一个解决方案。
此处有关标记的更多详细信息:
https://github.com/airbnb/react-native-maps/blob/master/docs/marker.md
注意:作为最佳实践,建议您在渲染时不要绑定。更好的解决方案是将它们添加到构造函数中,如下所示:
constructor (props) {
super(props);
this._onMarkerPress = this._onMarkerPress.bind(this);
}
或使用箭头功能。当我写答案时,我对此一无所知。