我正在使用LeafletJS
插件在ReactJS
单页应用程序中显示完整的页面地图。我遵循了这里的指示。但是,平铺的显示顺序不正确。它们是随机排列的(?)。我在这里发现了类似的问题,但在这种情况下,页面刷新的顺序被修复了。这对我来说不是真的。我的代码是(不包括样板):
index.html
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="stylesheets/atlas.css">
</head>
<body>
<div id="app">
Loading...
</div>
<script src="javascripts/atlas.js"></script>
</body>
</html>
index.js
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
)
应用程序.jsx
import LiveMap from './LiveMap';
// App component
const App = () => (
<LiveMap />
)
export default App;
LiveMap.jsx
class LiveMap extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div id='map'></div>
);
}
componentDidMount() {
let _map = this.map = L.map(ReactDOM.findDOMNode(this)).setView([-41.2858, 174.78682], 14);
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a> Contributors',
maxZoom: 18,
}).addTo(_map);
}
componentWillUnmount() {...}
shouldComponentUpdate() {return false;}
};
export default LiveMap;
我很确定您的问题是,在代码执行时,元素还没有完全呈现,或者,正如@ghybs所提到的,没有加载传单样式表。看看这个问题,尤其是第二个答案,它解决了这个问题:
使用componentDidUpdate或componentDidMount的一个缺点是,它们实际上是在绘制dom元素之前执行的,但在它们从React传递到浏览器的dom之后执行。
解决方案
为了绕过这一点,您必须将地图创建代码封装在setTimeout
中,如下所示:
componentDidMount() {
let element = ReactDOM.findDOMNode(this)
setTimeout(() => {
this.map = new L.map(element, {
center: new L.LatLng(41.019829, 28.989864),
zoom: 14,
maxZoom: 18,
layers: new L.TileLayer('...')
}, 100)
})
}
我把一支笔放在一起,上面展示了React组件中传单地图的一个工作示例。还要确保包含传单的样式表:
...
<head>
<link rel="stylesheet" href="stylesheets/atlas.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
</head>
...
我还建议使用ref
,我更新了笔以使用它。你可以在这里阅读更多参考文献。
相关问题
React和传单结合的好方法
渲染后反应