[英]TypeScript type for MapboxGLjs React ref hook
我正在嘗試為我在 React 中使用鈎子和 TypeScript 編寫的 mapboxgl 地圖添加一個源。
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'
});
});
我遇到以下錯誤:
“MutableRefObject”類型上不存在屬性“addSource”
如果沒有,我應該使用什么類型?
您希望在 ref 中保留一個mapboxgl.Map
,並且您還希望它在初始化之前為null
。 所以這意味着你的 ref 類型是:
const map = React.useRef<mapboxgl.Map | null>(null);
這很好解決(最好消除any
所有用途),但這與您遇到的錯誤無關。
當您擁有 ref 時,您始終可以通過current
屬性訪問它所引用的內容。 因此,您只需將最后一行更改為:
map.current.addSource(/* ... */)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.