简体   繁体   中英

React Passing a function as prop to child component, but the parent is not accessing the data provided by the child

the zoom is not updated into 13 i want the zoom variable to be changend in the parent component when passing the function handelzoom to the child component the zoom is still equal to 1, the position is found but the function handelzoom doesnt take 13 as a value

the parent:

import DraggableMarker from './draggablemarker/draggablemarker'
import React, {useState,useRef, useMemo,useCallback, useEffect} from "react";
import { MapContainer, TileLayer, Marker, Popup,useMapEvents } from 'react-leaflet';
 import MinimapControl from './minimapcontrol/minimapcontrol'

 import LocationMarker from './positionmarker/positionmarker'
import './App.css';


function App() {
  const POSITION_CLASSES = {
    bottomleft: 'leaflet-bottom leaflet-left',
    bottomright: 'leaflet-bottom leaflet-right',
    topleft: 'leaflet-top leaflet-left',
    topright: 'leaflet-top leaflet-right',
  }
  
  const BOUNDS_STYLE = { weight: 1 }
  const [map, setMap] = useState(null)
  const [zoom,setzoom]=useState(1)


const center = [51.505, -0.09]



function handlezoom(zoomi){
     //👇️ take parameter passed from Child component
  setzoom(zoomi)};


   return(
    <div>
   

    <MapContainer center={center} zoom={zoom} scrollWheelZoom={false}>
    <TileLayer
      attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
    {/* <DraggableMarker /> */}
    <LocationMarker handlezoom={handlezoom} />
    {/* <DraggableMarker /> */}
    <MinimapControl position="topright" />
  </MapContainer>
     </div>

  
   )

}

   
export default App;

the child:

import React,{useState} from 'react'
import { MapContainer, TileLayer, Marker, Popup,useMapEvents } from 'react-leaflet';
export default function LocationMarker({handlezoom}) {
    const [position, setPosition] = useState(null)
    const [haveuserlocation,sethaveuserlocation]= useState(false)
    
  const map = useMapEvents({
  
    click() {
      map.locate()
      handlezoom(13)
    },
    locationfound(e) {
      setPosition(e.latlng)
      map.flyTo(e.latlng, map.getZoom())
   
      
    },

    
  })

  return (position === null ? null :
   
     <Marker position={position}>
      <Popup>You are here</Popup>
    </Marker>
  )
  
  
    
  
}

want the zoom to have value of 1 at first and after finding the position it will take the value of 13 please help me在此处输入图像描述

pass setZoom

...
  <LocationMarker setZoom={setZoom} />
...


export default function LocationMarker({setZoom}) {


click() {
  map.locate()
  setZoom(13)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM