我如何从React的另一个组件分配一个功能的按钮?



我有一个Map组件,我创建了一个函数来获取用户的当前位置。我已经将这个地图组件导入到一个更大的RetailLocations组件中。我想将在Map组件中创建的handleClick()函数分配给RetailLocations组件中的一个按钮。相关代码:

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>
....

我还遗漏了什么吗?

你应该看看这个。组件是React不可分割的一部分。每个React应用程序由几个组件组成,每个组件可能需要触发各种操作的用户交互。为了实现用户交互,我们可以在React中调用函数和方法来完成特定的操作。我们使用这些操作将数据从父组件传递给子组件或从子组件传递给父组件。https://www.pluralsight.com/guides/how-to-reference-a-function-in-another-component

使用forwardRef和useImperativeHandle钩子来访问功能组件内部的方法。

映射组件:

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

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>
</>
}
....

最新更新