reactjs - MapboxGLjs React ref hook 的 TypeScript 类型
问题描述
我正在尝试为我在 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”
如果没有,我应该使用什么类型?
解决方案
您希望将 a 保留mapboxgl.Map
在 ref 中,并且您还希望它null
在初始化之前存在。这意味着您的参考类型是:
const map = React.useRef<mapboxgl.Map | null>(null);
这很好解决(最好消除 的所有用途any
),但这与您遇到的错误无关。
当你有一个 ref 时,你总是通过属性访问它所引用的内容current
。因此,您只需将最后几行更改为:
map.current.addSource(/* ... */)
推荐阅读
- java - 如何从服务器获取 CasToken?
- javascript - 如何在 TypeScript / JavaScript 中缩写驼峰式文本字符串
- angular - 如何有条件地允许导航到用户
- javascript - Jquery 动画滑块
- python - 为什么 Django 开发人员使用 Django 内置管理面板?是否说必须使用而不是 html 主题?
- node.js - 如何在 JSON 中表示元数据
- sql-server - PERFORMANCE - 按 SELECT UNION 中的特定查询块过滤
- android - Android Kotlin - Webview 数据库
- java - 我如何从数据库中选择一个特定的值
- sharepoint - 使用powerapps将元素从列表移动到共享点中的另一个列表