如何将状态向下传递给子组件的处理程序?
How to pass state down to child component's handler?
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
您应该可以参考 createPopup
中的状态。使用 useState
挂钩在 CovidMap
中创建和使用状态变量:
const CovidMap = () => {
...
const [properties, setProperties] = useState({}); // Defined BEFORE handler
const [layer, setLayer] = useState({}); // Defined BEFORE handler
const createPopup = () => {
layer.on({
mouseover: showCords,
});
layer.bindPopup(properties.NAME);
}
...
}
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
您应该可以参考 createPopup
中的状态。使用 useState
挂钩在 CovidMap
中创建和使用状态变量:
const CovidMap = () => {
...
const [properties, setProperties] = useState({}); // Defined BEFORE handler
const [layer, setLayer] = useState({}); // Defined BEFORE handler
const createPopup = () => {
layer.on({
mouseover: showCords,
});
layer.bindPopup(properties.NAME);
}
...
}