[英]Arbitrary function on react-leaflet marker click
React-leaflet 很好地提供了在標記的Popup
中放置內容的能力。
例如在我的例子中:
<Marker position={[item.lat, item.lng]} key={item.machineid}>
<Popup maxWidth={720}>
<ItemGrid machineid={item.machineid}
username={this.props.username}/>
</Popup>
</Marker>
但是,如果此內容太大,則可能會很笨拙,尤其是在移動設備上。 我想在單擊標記時激活(引導程序)模態界面。 有沒有辦法在反應傳單中做到這一點?
更新:事件行為#
使用 Marker 組件內的 eventHandlers 偵聽器函數:
<Marker
position={[50.5, 30.5]}
eventHandlers={{
click: (e) => {
console.log('marker clicked', e)
},
}}
/>
根據反應傳單文檔,
Leaflet 暴露自己的事件,與 React 不同。 您可以使用 React-Leaflet 通過向以 on 為前綴的屬性添加回調來收聽它們。 例如:
<Map onMoveend={this.handleMoveend}>...</Map>
。查看🍃 Leaflet 的文檔,了解與每個組件相關的事件。
因此我們可以使用 Leaflet 的原生onClick DOM 事件。
使用react-leaflet
,它看起來像這樣:
import React, { Component } from "react"
import { Map as LeafletMap, TileLayer, Marker } from "react-leaflet"
class Map extends Component {
handleClick = event => {
const { lat, lng } = event.latlng
console.log(`Clicked at ${lat}, ${lng}`)
}
render () {
return (
<LeafletMap center={[52.5134, 13.4225]} zoom={13}>
<TileLayer attribution={attribution} url={url}>
<Marker
position={[52.5134, 13.4225]}
onClick={this.handleClick} // <-- call handleClick()
/>
</TileLayer>
</LeafletMap>
)
}
}
export default Map
我發現了一種在點擊標記時執行任意操作的技巧。 (1) 保留彈出窗口,但讓它的內容隨心所欲(例如,默認打開一個模式) 和 (2) 用 CSS 隱藏彈出窗口的容器 div。
就我而言,它看起來像這樣:地圖視圖,保持不變:
<Marker position={[item.lat, item.lng]} key={item.machineid}>
<Popup maxWidth={720}>
<ItemGrid machineid={item.machineid}
username={this.props.username}/>
</Popup>
</Marker>
然后之前在彈出窗口中的 ItemGrid 更改為包含一個模式。 (這里我們使用 reactstrap 組件,並在組件安裝時將 modal 設置為true
。):
class ItemGrid extends Component {
constructor(props){
super(props);
this.state = {modal:false}
this.toggle = this.toggle.bind(this);
}
toggle() {
this.setState({
modal: !this.state.modal
});
}
componentDidMount() {
this.setState({modal:true})
}
render() {
return (
<div>
<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
<ModalHeader toggle={this.toggle}>Modal Header</ModalHeader>
<ModalBody>
{ContentThatWasPreviouslyInPopup}
</ModalBody>
</Modal>
</div>
最后在傳單 CSS 中:
.leaflet-container a.leaflet-popup-close-button {
position: absolute;
top: 0;
right: 0;
padding: 8px 8px 0 0;
text-align: center;
width: 0px;
height: 0px;
font: 0px/0px Tahoma, Verdana, sans-serif; //DANGEROUS HACK
color: #c3c3c3;
text-decoration: none;
font-weight: bold;
background: transparent;
}
.leaflet-popup-content-wrapper {
padding: 1px;
text-align: left;
border-radius: 12px;
width: 0px // DANGEROUS HACK
}
對於想要傳遞參數的人,您應該使用:
<Marker
position={[50.5, 30.5]}
data="FooBar"
eventHandlers={{
click: (e) => {
console.log(e.target.options.data); // will print 'FooBar' in console
},
}}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.