GeoJson组件有一个函数onEachFeature,它调用一个处理程序,在本例中是createPopup。
<GeoJSON data={covidGeoJSON} onEachFeature={createPopup}></GeoJSON>
在处理程序createPopup中,如何访问在CovidMap组件中定义的状态?
import React, { useState } from 'react'
import { MapContainer, GeoJSON } from 'react-leaflet'
import 'leaflet/dist/leaflet.css'
CovidMap = ({ covidGeoJSON, styles }) => {
const showCords = (e) => {
console.log(e.latlng);
}
const createPopup = (state, layer) => {
layer.on({
mouseover: showCords,
});
layer.bindPopup(state.properties.NAME);
}
const [range, setRange] = useState([]);
return (
<div>
<MapContainer style={{ height: '90vh', width: '100vw' }} center={[39.162497380360634, -94.83672007881789]} zoom={5}>
<GeoJSON data={covidGeoJSON} onEachFeature={createPopup}></GeoJSON>
</MapContainer>
</div>
)
}
export default CovidMap发布于 2022-03-05 20:14:20
您应该能够从createPopup引用状态。使用CovidMap钩子在useState中创建和使用状态变量:
const CovidMap = () => {
...
const [properties, setProperties] = useState({});
const [layer, setLayer] = useState({});
const createPopup = () => {
layer.on({
mouseover: showCords,
});
layer.bindPopup(properties.NAME);
}
...
}https://stackoverflow.com/questions/71365187
复制相似问题