[英]why leaflet map doesn't render on react app
我在js
實現中包含了傳單地圖,而不是jsx
實現,但是我遇到了一個問題,因為它超出了它的范圍。
這是我導入傳單的方式:
import L from 'leaflet';
並實施:
componentDidMount() {
// create map
this.map = L.map('map', {
center: [49.8419, 24.0315],
zoom: 16,
layers: [
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}),
]
});
}
和用法:
<div id={"map"} >
您尚未在index.html
添加傳單 css 文件。
對於傳單版本1.3.4
,將以下內容添加到 index.html
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css"
integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
crossorigin=""/>
在您的地圖組件 css 文件中,使用所需的高度和寬度覆蓋leaflet-container
類。
.leaflet-container {
height: 600px;
width: 100%;
}
添加后,使用react-leaflet
Map
和TileLayer
組件來渲染地圖。
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Map, TileLayer } from "react-leaflet";
import "./styles.css";
class App extends Component {
state = {
center: [51.505, -0.091],
zoom: 13
};
render() {
return (
<div>
<Map center={this.state.center} zoom={this.state.zoom}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
</Map>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
您可以在此處找到工作代碼。 https://codesandbox.io/s/2wnv7o1mlr
是的,您缺少 css 文件。
順便說一句,這不是您應該如何使用react-leaflet
。 componentDidMount 不是做你正在做的事情的地方。 把它放在渲染中
import { Map, TileLayer } from 'react-leaflet';
<Map>
<TileLayer url="'http://{s}.tile.osm.org/{z}/{x}/{y}.png'" />
</Map>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.