我正在使用 react-leaflet 并想向 map 添加图例。
我目前可以通过将 map 的引用传递给自定义组件并呈现 null 来实现,同时让函数创建 HTML 并将其添加到 map 。使用 Jest 和 Enzyme 进行测试时,裁判是一场噩梦。
有没有办法使用 react-leaflet 组件来完成这个?
最佳答案
您可以通过扩展react-leaflet
的MapControl
类并使用例如Leaflet 官方页面教程为Using GeoJSON with Leaflet 提供的图例代码来实现。 .
class Legend extends MapControl {
componentDidMount() {
// place your code here
...
const legend = L.control({ position: "bottomright" });
...
const { map } = this.props.leaflet;
legend.addTo(map);
}
}
然后在这里导入:
<Map style={{ height: "100vh" }} center={position} zoom={13}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Legend />
</Map>
关于javascript - 如何在不使用 refs 和手动修改 DOM 的情况下使用 React 传单向 map 添加图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57403442/