【发布时间】:2021-10-09 18:15:43
【问题描述】:
我有一个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='© <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>
....
我还有什么遗漏的吗?
【问题讨论】:
-
我觉得这是
Map组件可能应该订阅某些事件源(例如可观察对象)的情况之一,该事件源会发出坐标,然后您只需从应用中的其他地方。 -
组件不能返回额外的变量。但是为什么不简单地将 handleClick 逻辑移动到
RetailLocations?
标签: javascript reactjs onclick event-handling