在 React + Typescript Web 应用程序中,我希望能够以编程方式显示/隐藏传单绘制“绘制折线”按钮。
为了执行此任务,我对 EditControl 的绘制属性进行了操作,如本例所示(代码沙箱位于:https ://codesandbox.io/s/leaflet-toggle-button-0hbr0?file=/src/MyMap.tsx:0 -1257 )
import React, { useState } from "react";
import { MapContainer, TileLayer, FeatureGroup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-draw/dist/leaflet.draw.css";
import { EditControl } from "react-leaflet-draw";
import "leaflet-draw";
const MyMap = () => {
const [showButton, setShowButton] = useState<boolean>(true);
return (
<>
<button
onClick={() => {
setShowButton((oldValue) => !oldValue);
}}
>
Toggle
</button>
<p>{"Show button: " + showButton}</p>
<MapContainer
center={[37.8189, -122.4786]}
zoom={13}
style={{ height: "300px" }}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
<FeatureGroup>
<EditControl
position="topright"
draw={{
rectangle: false,
circle: false,
circlemarker: false,
polygon: false,
marker: false,
polyline: showButton
}}
/>
</FeatureGroup>
</MapContainer>
</>
);
};
export default MyMap;
该按钮最初是显示的,并且在单击“切换”按钮后,它正确地消失了。
不幸的是,再次按下“切换”按钮,它不再出现。
实现正确行为的正确方法是什么?
编辑:根据https://github.com/Leaflet/Leaflet.draw#user-content-example-leafletdraw-config,
您可以在初始化后使用 Leaflet.draw 控件上的 setDrawingOptions 方法更改绘图处理程序选项。
不幸的是,我也没有设法调用该方法。