如何将状态向下传递给子组件的处理程序?

kqlmhetl  于 2022-09-21  发布在  React
关注(0)|答案(1)|浏览(152)

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
sr4lhrrt

sr4lhrrt1#

您应该能够引用createPopup中的状态。使用useState挂钩在CovidMap中创建和使用状态变量:

const CovidMap = () => {

    ...
    const [properties, setProperties] = useState({});
    const [layer, setLayer] = useState({});

    const createPopup = () => {
        layer.on({
            mouseover: showCords,
        });
        layer.bindPopup(properties.NAME);
    }
    ...
}

相关问题