我刚刚开始在我的react-mapbox-gl应用程序中使用react-mapbox-gl-draw
。我正在按照this进行非常快速的演示,并按照他们的docs来设置<DrawControl />
。看起来很简单,但是我遇到了一个问题。
这是我的代码,错误如下:
import DrawControl from 'react-mapbox-gl-draw';
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css';
// imports
// ignore the class instantiation, constructor, all that. It works.
// in the render method:
<Map
onStyleLoad={ el => this.map = el}
style={this.state.style}
containerStyle={{
height: this.state.height,
width: this.state.width
}}
center={[0,0]}
zoom={[2]} >
<DrawControl />
</Map>
这是错误:
index.js:14 Uncaught TypeError: map.getStyle is not a function
at DrawControl.componentDidMount (index.js:14)
at commitLifeCycles (react-dom.development.js:14361)
at commitAllLifeCycles (react-dom.development.js:15462)
at HTMLUnknownElement.callCallback (react-dom.development.js:100)
at Object.invokeGuardedCallbackDev (react-dom.development.js:138)
at invokeGuardedCallback (react-dom.development.js:187)
at commitRoot (react-dom.development.js:15603)
at completeRoot (react-dom.development.js:16618)
at performWorkOnRoot (react-dom.development.js:16563)
at performWork (react-dom.development.js:16482)
at performSyncWork (react-dom.development.js:16454)
at requestWork (react-dom.development.js:16354)
at scheduleWork$1 (react-dom.development.js:16218)
at Object.enqueueSetState (react-dom.development.js:11299)
at ReactMapboxGl.../../../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:335)
at r.<anonymous> (map.js:119)
at r.Ft.fire (mapbox-gl.js:29)
at r._render (mapbox-gl.js:33)
at mapbox-gl.js:33
或多或少,显然<DrawControl />
试图在组件(地图)挂载后立即调用方法,但是我不确定为什么或如何修复它。我将不胜感激!
-编辑-
我在地图对象中添加了MapContext.Consumer
,因为它抱怨要使用map
对象。所以现在正在安装,但看不到绘制对象。有任何想法吗?
这是我更新的代码:
<Map
onStyleLoad={ el => this.map = el}
style={this.state.style}
containerStyle={{
height: this.state.height,
width: this.state.width
}}
center={[0,0]}
zoom={[2]} >
<MapContext.Consumer>
{(map) => {
<DrawControl />
}}
</MapContext.Consumer>
</Map>
答案 0 :(得分:0)
因此解决方案是在MapboxDraw
内实现MapContext.Consumer
。这是下面的MapboxDraw
的摘录,也是这里的link。之所以可行,是因为它可以访问地图对象,并且可以直接在地图上绘制。
var draw = new MapboxDraw({
displayControlsDefault: false,
controls: {
polygon: true,
trash: true
}
});