如何使传单弹出窗口在单击列表按钮时显示



我正在尝试用反应传单测试一些东西。我在地图上显示 2 台不同的机器,当我单击特定的列表按钮(由机器 ID 区分(时,它会将地图的中心移动到该机器的位置坐标。弹出窗口已经添加,但它们仅在我单击地图上的标记时显示。我希望每当我单击列表按钮时弹出窗口都会自动显示(目前我必须单击地图上的标记才能弹出(,并且它应该像通常的正常行为一样关闭(这是默认的(。知道我该怎么做吗?

PS:我尝试使用refs,即使这样,它也部分工作。 ...

export default class App extends React.Component {
constructor() {
super();
this.state = {
location: [
{
id: 1,
machine: 1,
lat: 51.503,
lng: -0.091
},
],         
};
}
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='&amp;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>
);
})}


</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>
}
</>
);
}
}

你定义引用的方式是行不通的。 当您尝试在map语句中添加 refs 时,您需要一个数组来跟踪这些 ref。 在构造函数中:

this.markerRefs = []

然后在每个标记中,将 ref 添加到该数组:

<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()
}

这是一个有效的代码沙箱

最新更新