Kyl*_*yle 2 typescript reactjs mapbox-gl-js
我正在尝试为我的 mapboxgl 地图添加源,该地图是我用钩子和 TypeScript 在 React 中编写的。
export default function App() {
const mapContainer = React.useRef<any>(null);
const map = React.useRef<any>(null);
const [lng, setLng] = React.useState(-74.0632);
const [lat, setLat] = React.useState(40.7346);
const [zoom, setZoom] = React.useState(12);
React.useEffect(() => {
if (map.current) return; // initialize map only once
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: 'mapbox://styles/mapbox/streets-v11',
center: [lng, lat],
zoom: zoom
});
map.addSource('property-data', {
type: 'geojson',
data: 'path/to/data.geojson'
});
});
Run Code Online (Sandbox Code Playgroud)
我遇到以下错误:
属性“addSource”在类型“MutableRefObject”上不存在
如果没有的话我应该使用什么类型?
您希望mapboxgl.Map在引用中保留 a ,并且还希望它null在初始化之前。这意味着您的引用类型是:
const map = React.useRef<mapboxgl.Map | null>(null);
Run Code Online (Sandbox Code Playgroud)
这很好修复(最好消除 的所有使用any),但这与您收到的错误无关。
当您拥有引用时,您始终可以通过属性访问它所引用的内容current。因此,您只需将最后一行更改为:
map.current.addSource(/* ... */)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4145 次 |
| 最近记录: |