如何解决如何使用 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='© <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
的 react 组件。两者都可以更轻松地使用引导程序组件,否则您将不得不自己创建和操作状态。
这是一个带有 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>
);
}
在您的地图上导入您的自定义模式并处理其状态以便能够在按下按钮时显示隐藏
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='© <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
库似乎存在错误。当您打开模态然后将其关闭时,地图意外冻结并且您无法与其进行交互。
我用 reactstrap
安装并复制了它,没有出现这样的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。