下面是我的OpenLayers组件的代码:
import React, { useState, useEffect, useRef } from 'react';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
function OpenLayer(props) {
const [map, setMap] = useState();
const mapElement = useRef();
const mapRef = useRef();
mapRef.current = map;
useEffect(() => {
const initialMap = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM(),
}),
],
view: new View({
center: [0, 0],
zoom: 0,
}),
});
setMap(initialMap);
}, []);
return (
<div>
<div ref={mapElement} className="map-container" />
</div>
);
}
export default OpenLayer;
我在我的主应用程序中这样渲染它:
<Row className="mapRow">
<OpenLayer />
</Row>
我似乎不能得到任何东西返回...哦,这是我的css太:
.mapRow{
text-align: center;
height: 100%;
width: 100%;
}
.map-container{
height: 100vh;
width: 100%;
}
是不是有什么明显的东西我忽略了?
2条答案
按热度按时间xytpbqjk1#
好吧,你只是用错误的方式初始化它,你仍然在
map
类中初始化map,但是你需要用你当前的map ref来初始化它,所以你需要在初始化阶段使用mapElement
而不是map
。所以应该是这样的:
工作演示:
lsmd5eda2#
在useEffect结束时,你应该添加的另一个东西是
return () => initialMap.setTarget(null)
,这将在Map组件卸载时释放Map资源。