• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

366
Views
¿Cómo asigno una función a un botón de otro componente en React?

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='&copy; <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?

almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

almost 3 years ago · Juan Pablo Isaza Report

0

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='&copy; <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> </> } ....
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error