我使用以下代码但没有成功:
//在NativeBase容器内部
- <MapView.Animated
- ref="map"
- style = {styles.map}
- showsUserLocation = {true}
- zoomEnabled = {true}
- showsMyLocationButton = {true}
- showsCompass = {true}
- showScale = {true}
- showsIndoors = {true}
- mapType = {this.state.mapTypes[this.state.mapTypeCode]}
- />
//在类的componentDidMount内部
- navigator.geolocation.getCurrentPosition(
- (position) => {
- var initialPosition = JSON.stringify(position.coords);
- this.setState({position: initialPosition});
- let tempCoords = {
- latitude: Number(position.coords.latitude),longitude: Number(position.coords.longitude)
- }
- this.refs.map.animateToCoordinate(tempCoords,1);
- },function (error) { alert(error) },);
解决方法
我有一些问题,其中this.refs是未定义的,除非我在构造函数中将对此的引用绑定到我使用this.refs的函数.在你的情况下,试试这个:
- constructor(props) {
- super(props);
- this._getCoords = this._getCoords.bind(this);
- this.state = {
- position: null
- };
- }
- componentDidMount() {
- this._getCoords();
- }
- _getCoords = () => {
- navigator.geolocation.getCurrentPosition(
- (position) => {
- var initialPosition = JSON.stringify(position.coords);
- this.setState({position: initialPosition});
- let tempCoords = {
- latitude: Number(position.coords.latitude),longitude: Number(position.coords.longitude)
- }
- this._map.animateToCoordinate(tempCoords,1);
- },);
- };
- render() {
- return (
- <MapView.Animated
- ref={component => this._map = component}
- />
- );
- }
虽然仍然可以使用字符串引用,但我相信这是遗留的,所以我也将MapView引用更新为更新的方式.见:Ref Example