我正在尝试使用react传单进行测试。我在地图上显示2台不同的机器,当我单击特定的列表按钮(按机器ID区分)时,它将地图中心移动到该机器的位置坐标。弹出窗口已经添加,但是仅当我单击地图上的标记时才会显示。我希望每当我单击列表按钮时都自动显示弹出窗口(当前,我必须单击地图上的标记以使其弹出),并且它应该像通常的正常行为一样关闭(默认情况下)。知道我该怎么做吗?
PS:我尝试使用refs,即使它部分起作用。...
import React from "react";
import { List, ListItem } from "@material-ui/core";
import { Map, Marker, Popup, TileLayer } from "react-leaflet";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import "./styles.css";
import Icon from "../src/icon.png";
import shadow from "../src/shadow.png";
export default class App extends React.Component {
constructor() {
super();
this.state = {
location: [
{
id: 1,
machine: 1,
lat: 51.503,
lng: -0.091
},
{
id: 2,
machine: 2,
lat: 51.56,
lng: -0.094
}
],
center: [51.505, -0.091],
zoom: 11,
marker: null
};
this.clickAction = this.clickAction.bind(this);
}
Icon = L.icon({
iconUrl: Icon,
shadowUrl: shadow,
iconSize: [38, 50],
shadowSize: [50, 64],
iconAnchor: [22, 34], // point of the icon which will correspond to marker's location
shadowAnchor: [4, 62],
popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
});
openPopUp(marker, id) {
if (marker && marker.leafletElement) {
marker.leafletElement.openPopup(id);
}
}
clickAction(id, lat, lng) {
this.setState({ marker: id, zoom: 16, center: [lat, lng] });
}
render() {
console.log(this.state);
return (
<>
<Map center={this.state.center} zoom={this.state.zoom}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
{this.state.location.map(({ lat, lng, id }) => {
return (
<Marker
position={[lat, lng]}
icon={this.Icon}
ref={this.openPopUp(id)}
>
<Popup> {id} </Popup>
</Marker>
);
})}
{/* {this.state.location.map(({ lat, lng, id }, index) => {
<Marker position={[lat, lng]} icon={this.Icon}>
<Popup>{id}</Popup>
</Marker>;
switch (this.state.marker) {
case id:
return (
<Marker key={id} position={[lat, lng]} icon={this.Icon}>
<Popup>{id}</Popup>
</Marker>
);
}
})} */}
</Map>
{
<List style={{ width: "20%", float: "left" }}>
{this.state.location.map(({ id, machine, lat, lng }) => {
return (
<ListItem
key={id}
button
onClick={() => {
this.clickAction(id, lat, lng);
}}
>
Id {id} <br />
machine {machine}
</ListItem>
);
})}
</List>
}
</>
);
}
}
...
我的样本https://codesandbox.io/s/gallant-star-m42qe?file=/src/App.js
您定义裁判的方式行不通。如果您正在尝试在map
语句中添加引用,则需要一个数组来跟踪这些引用。在您的构造函数中:
this.markerRefs = []
然后在每个标记中,将引用添加到该数组:
<Marker
position={[lat, lng]}
icon={this.Icon}
ref={ref => this.markerRefs[id] = ref} >
{ ... }
</Marker>
现在您的标记具有唯一的引用,您可以在clickAction
函数中使用它们:
clickAction(id, lat, lng) {
this.setState({ marker: id, zoom: 16, center: [lat, lng] });
this.markerRefs[id].leafletElement.openPopup()
}