如何在Mapbox地图加载事件中访问React组件Props
解决Mapbox地图load事件中无法访问this.props的问题
这个问题我之前也碰到过,核心原因就是普通函数作为load事件的回调时,this的上下文会变成Mapbox地图实例,而不是你的React组件实例,所以访问不到this.props和this.map。给你几个简单的解决办法:
方案1:使用箭头函数(最推荐)
箭头函数不会创建自己的this,它会继承外层作用域的this,也就是你的组件实例。修改后的代码如下:
componentDidMount() { this.map = new mapboxgl.Map({ container: this.mapContainer, style: "#my_url_style#", center: [this.state.lng, this.state.lat], zoom: this.state.zoom }); // 改用箭头函数作为回调 this.map.on("load", () => { this.map.addLayer(this.props.dataLayers[0]); }); }
方案2:提前保存this到变量
在回调函数外部把组件的this保存到一个变量(比如that或者self),然后在回调里用这个变量访问组件的属性:
componentDidMount() { this.map = new mapboxgl.Map({ container: this.mapContainer, style: "#my_url_style#", center: [this.state.lng, this.state.lat], zoom: this.state.zoom }); const that = this; this.map.on("load", function(){ that.map.addLayer(that.props.dataLayers[0]); }); }
方案3:用bind绑定this
通过bind()方法手动把回调函数的this绑定到组件实例:
componentDidMount() { this.map = new mapboxgl.Map({ container: this.mapContainer, style: "#my_url_style#", center: [this.state.lng, this.state.lat], zoom: this.state.zoom }); this.map.on("load", function(){ this.map.addLayer(this.props.dataLayers[0]); }.bind(this)); // 绑定组件的this到回调函数 }
这三种方法都能解决你的问题,个人最推荐第一种箭头函数的写法,代码更简洁直观,也符合现代React的写法习惯。
内容的提问来源于stack exchange,提问作者Rumpelstinsk
相关产品推荐
相关产品推荐

