Tengo un componente Map
donde creé una función para obtener la ubicación actual del usuario. Importé este componente de mapa a un componente RetailLocations
más grande. Quiero asignar la función handleClick()
creada en el componente Map
a un botón en el componente RetailLocations
. El código correspondiente:
Map Component code:
const [center, setCenter] = useState({ lat: 0, lng: 0 }); const location = useGeoLocation(); const mapRef = useRef(); const ZOOM_LEVEL = 20; const handleClick = (e) => { if (location.loaded) { mapRef.current.leafletElement.flyTo( [location.coordinates.lat, location.coordinates.lng], ZOOM_LEVEL, { animate: true } ); } }; return <> <MapContainer center={center} zoom={ZOOM_LEVEL} ref={mapRef} scrollWheelZoom={false} className={style.mapContainer} > <TileLayer attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' /> {location.loaded && ( <Marker position={[ location.coordinates.lat, location.coordinates.lng ]}></Marker> )} </MapContainer> </>; }; export default Map;
This is the RetailLocations component's relevant code:
import Map from './Map'; .... <button className={style.locationBtn} onClick={handleClick} >My Location</button> ....
¿Hay algo más que me estoy perdiendo?
deberías leer esto de pluralsight: Los componentes son una parte integral de React. Cada aplicación React consta de varios componentes, y cada componente puede requerir la interacción del usuario que desencadena varias acciones. Para lograr la interactividad del usuario, podemos llamar a funciones y métodos para realizar operaciones específicas en React. Pasamos datos de componentes primarios a secundarios o secundarios a primarios mediante estas acciones. https://www.pluralsight.com/guides/how-to-reference-a-function-in-another-component
Use los ganchos forwardRef y useImperativeHandle para acceder al método dentro de un componente funcional.
Componente de mapa:
import { forwardRef, useImperativeHandle } from 'react' const Map = forwardRef((props, ref) => { ... const handleClick = (e) => { if (location.loaded) { mapRef.current.leafletElement.flyTo( [location.coordinates.lat, location.coordinates.lng], ZOOM_LEVEL, { animate: true } ); } }; useImperativeHandle( ref, () => ({ handleClick }), [handleClick] ); return <> <MapContainer center={center} zoom={ZOOM_LEVEL} ref={mapRef} scrollWheelZoom={false} className={style.mapContainer} > <TileLayer attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' /> {location.loaded && ( <Marker position={[ location.coordinates.lat, location.coordinates.lng ]}></Marker> )} </MapContainer> </>; })
Componente RetailLocations:
import Map from './Map'; import { useRef } from 'react'; .... const RetailLocations = () => { const ref = useRef() return <> <Map ref={ref} /> <button className={style.locationBtn} onClick={(e) => ref.current.handleClick(e)}> My Location </button> </> } ....