【发布时间】:2021-12-20 18:47:51
【问题描述】:
我的 Ionic React 应用程序中有一个 React-Leaflet 映射,其中包含一些 Leaflet 功能。我添加了具有多个功能的行 (GeoJSON),并为每个功能添加了一个弹出窗口,可以通过单击该功能来访问。在这个弹出窗口中,我想要一个按钮来将部分弹出窗口复制到剪贴板。对于复制,我使用Capacitor Clipboard。弹出窗口和复制代码都在工作,只是没有按照我在弹出窗口中设置的方式工作,我不知道如何让它按照我想要的方式运行......
我面临的问题是,一旦地图被渲染,该函数就会被自动调用,这会导致应用程序崩溃并关闭。但我只希望在单击弹出窗口中的按钮时执行该函数,如果不应该复制任何内容。
我发现了一些类似的问题,但通常答案是使用onClick={()=>{function()}},但这不适用于传单弹出窗口......而且我认为可能有更好的方法来触发onclick="+writeToClipboard(part, id)+",但我的东西试过不行
function LeafletMap() {
const [map, setMap] = useState(null)
const geoJsonRef = useRef();
const writeToClipboard = async (part, id) => {
var copyText = JSON.stringify(part.concat(id));
await Clipboard.write({
string: copyText
});
};
const onEachClick = (info, layer) => {
const part = info.properties.Objekt_ID
const id = info.properties.FID_
layer.bindPopup(
"Objekt ID: <b>" + part + "</b><br>Abschnitt ID: <b>" + id + "</b><br><button onclick="+writeToClipboard(part, id)+">Copy to Clipboard</button>"
);
layer.on({ click: handleFeatureClick });
};
const handleFeatureClick = (e) => {
if (!geoJsonRef.current) return;
geoJsonRef.current.resetStyle();
const layer = e.target;
layer.setStyle({ color: "red" });
};
const displayMap = useMemo(
() => (
<MapContainer
center={position}
zoom={zoom}
scrollWheelZoom={false}
whenCreated={setMap}>
<LayersControl position="topright">
<LayersControl.BaseLayer checked name="OpenStreetMap - Karte">
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png"
/>
</LayersControl.BaseLayer>
<LayersControl.BaseLayer name="Esri - Satellit">
<TileLayer
attribution='Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
/>
</LayersControl.BaseLayer>
</LayersControl>
<GeoJSON data={PL.features} onEachFeature={onEachClick} ref={geoJsonRef}/>
<GeoJSON data={WWD.features} onEachFeature={onEachClick} ref={geoJsonRef}/>
</MapContainer>
),
[],
)
window.dispatchEvent(new Event('resize'));
return (
<div>
{displayMap}
</div>
)
}
export { LeafletMap }
【问题讨论】:
-
能否提供完整的代码sn-p?
-
@RandyCasburn 感谢您提供的信息!我尝试使用 const btn 访问按钮,但它给了我错误:“btn is null”
-
@PaulFitzgerald 我更新了代码块,但它只是一个组件,我显示在我的一个应用程序选项卡中
标签: javascript reactjs ionic-framework leaflet