[英]How do I assign a function to a button from another component in React?
我有一个Map
组件,我在其中创建了一个 function 来获取用户的当前位置。 我已将此 map 组件导入到更大的RetailLocations
组件中。 我想将在RetailLocations
组件中创建的handleClick()
function 分配给Map
组件中的一个按钮。 相关代码:
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>
....
还有什么我想念的吗?
你应该读这个。 来自 pluralsight:组件是 React 不可或缺的一部分。 每个 React 应用程序都包含多个组件,每个组件可能需要触发各种操作的用户交互。 为了实现用户交互,我们可以在React中调用函数和方法来完成特定的操作。 我们使用这些操作将数据从父组件传递到子组件或从子组件传递到父组件。 https://www.pluralsight.com/guides/how-to-reference-a-function-in-another-component
使用 forwardRef 和 useImperativeHandle 挂钩访问功能组件内的方法。
Map 组件:
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>
</>;
})
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>
</>
}
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.