繁体   English   中英

React 将 function 作为 prop 传递给子组件,但父组件未访问子组件提供的数据

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

缩放未更新为 13 我希望在将 function handelzoom 传递给子组件时更改父组件中的缩放变量缩放仍然等于 1,找到 position 但 function handelzoom 不将 13 作为值

父母:

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;

孩子:

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>
  )
  
  
    
  
}

首先希望缩放的值为 1,在找到 position 后它将取值为 13,请帮助我在此处输入图像描述

通过设置缩放

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


export default function LocationMarker({setZoom}) {


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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