React Leaflet divIcon 带有可点击按钮

问题描述 投票:0回答:1

在react-leaflet中,我尝试向地图添加一个可拖动按钮,如下图所示。我还希望 div 的其余部分不可点击。

Project screenshot

但是,当我单击按钮时,没有任何反应。

我希望当我单击按钮时,会触发handleClick 函数。

以下是该项目的代码。

IconWithButton.js

import { MapContainer, TileLayer, Marker } from "react-leaflet";
import { divIcon, Point } from "leaflet";
import { renderToString } from "react-dom/server";
import "leaflet/dist/leaflet.css";

function handleClick() {
  alert("Button Clicked!");
}

function ExampleIcon() {
  return (
    <div style={{ backgroundColor: "green" }}>
      <h1>Non-clickable text</h1>
      <button onClick={handleClick}>Clickable Button</button>
    </div>
  );
}

const customIcon = divIcon({
  html: renderToString(<ExampleIcon />),
  className: "",
  iconSize: new Point(250, 250),
});

function IconWithButton() {
  return (
    <div style={{ height: "1000px" }}>
      <MapContainer
        center={[51.505, -0.09]}
        zoom={13}
        scrollWheelZoom={true}
        style={{ height: "100%" }}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={[51.505, -0.09]} icon={customIcon} draggable={true} />
      </MapContainer>
    </div>
  );
}
export default IconWithButton;

Codesandboxhttps://codesandbox.io/p/sandbox/react-leaflet-button-icon-mtxpl5?file=%2Fsrc%2FIconWithButton.js%3A10%2C25

javascript reactjs leaflet react-leaflet
1个回答
0
投票

您可以使用

click
eventHandlers prop 中的
<Marker>
事件,而不是向按钮添加单击处理程序。在点击事件处理函数中,您可以检查事件源自的 HTML 元素(即用户点击的内容),并且仅在按钮为情况下才执行操作:

<Marker
  ...
  eventHandlers={{
    click: (e) => {
      if (e.originalEvent.target.id === "myButton") {
        alert("x");
      }
    },
  }}
/>

要实现此功能,您需要为按钮提供一个 ID,以便您可以确定是否单击了该按钮:

<button id="myButton">Clickable Button</button>

代码沙箱 表明这种方法有效。

© www.soinside.com 2019 - 2024. All rights reserved.