簡體   English   中英

如何使用 react-leaflet 打開模式?

[英]How can I open a modal using react-leaflet?

我正在嘗試使用庫 react-leaflet ,當我們單擊彈出窗口上的按鈕時,我想打開一個模式,但我沒有做到這一點。

這是我的代碼:

import React from "react";
import { Map, TileLayer, Marker, Popup } from "react-leaflet";
import { defaultMarker } from "./defaultMarker";
import { popupContent, popupHead, popupText, okText } from "./popupStyles";
import "./Map.css";

const center = [51.505, -0.09];

const MapComp = () => {
  return (
    <Map style={{ width: "100%", height: "100vh" }} center={center} zoom={13}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      <Marker position={center} icon={defaultMarker}>
        <Popup className="request-popup">
          <button>Open Modal</button>
        </Popup>
      </Marker>
      }
    </Map>
  );
};

export default MapComp;

你可以在那里看到完整的代碼:

https://codesandbox.io/s/how-to-style-the-react-leaflet-popup-forked-7yozy?file=/src/Map.js:0-788

當我單擊彈出窗口並單擊“打開模態”按鈕時,我只是打開了一個模態

非常感謝 !

您可以使用react-bootstrap ,其中包含引導庫或reactstrap的反應組件。 兩者都可以更輕松地使用引導組件,否則您將不得不自己創建並操作 state。

這是react-bootstrap的示例:

安裝庫npm i react-bootstrap

創建模態組件:

function CustomModal({ show, onClose }) {
  return (
    <Modal show={show} onHide={onClose}>
      <Modal.Header closeButton>
        <Modal.Title>Modal heading</Modal.Title>
      </Modal.Header>
      <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
      <Modal.Footer>
        <Button variant="secondary" onClick={onClose}>
          Close
        </Button>
        <Button variant="primary" onClick={onClose}>
          Save Changes
        </Button>
      </Modal.Footer>
    </Modal>
  );
}

在您的 Map 上導入您的自定義模態並處理其 state 以便能夠在按下按鈕時顯示隱藏它

const MapComp = () => {
  const [show, setShow] = useState(false);

  const handleClose = () => setShow(false);

  return (
    <>
      <Map style={{ width: "100%", height: "100vh" }} center={center} zoom={13}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
        <Marker position={center} icon={defaultMarker}>
          <Popup className="request-popup">
            <button onClick={() => setShow(true)}>Open Modal</button>
          </Popup>
        </Marker>
      </Map>
      <Modal show={show} onClose={handleClose} />
    </>
  );
};

演示

編輯

react-bootstrap庫似乎存在錯誤。 當您打開模態然后關閉它時,map 會意外凍結,您無法與之交互。

我用reactstrap安裝並復制了它,沒有這樣的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM