gpt4 book ai didi

javascript - 如何以编程方式从另一个组件触发标记组件事件

转载 作者:行者123 更新时间:2023-12-03 00:07:56 26 4
gpt4 key购买 nike

使用 React Leaflet,我尝试从同级组件触发 Marker 组件的“click”事件。在常规传单中,这是使用如下内容完成的:

L.marker(lng,lat).fire('click');
L.marker(lng,lat).openPopup();

在“结果”组件中,我有一个结果列表,单击该列表时,我想触发 map 上标记组件的事件。

render() { 
<Results tileClicked2={this.tileClicked3.bind(this)} items={this.state.items}></Results>
<Map ref={m => { this.leafletMap = m; }}>
<TileLayer .../>
{this.state.items.map((value, index) => {
return (<Marker>...</Marker>)
}

在我的“tileClicked3”函数中,我能够记录this.leafletMap

tileClicked3(index){    
console.log(index);
console.log(this.leafletMap)
//I want to do:
// marker.fire();
// marker.openPopup();
}

这是单击时的控制台日志:

enter image description here

我想我一定很接近,但也许不是。

如有任何建议,我们将不胜感激...

最佳答案

这可以通过将单击的项目索引保持在状态并获取该索引处的标记项目并渲染它来完成。

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Map, TileLayer, Marker } from "react-leaflet";
import "./styles.css";

const listData = [
{
id: 1,
text: "Location A",
lng: 24.960937499999996,
lat: 38.54816542304656
},
{
id: 2,
text: "Location B",
lng: -103.71093749999999,
lat: 40.97989806962013
},
{
id: 3,
text: "Location C",
lng: 76.9921875,
lat: 24.84656534821976
}
];

const List = ({ onListItemClick }) => (
<div>
<ul>
{listData.map((aLocation, index) => (
<li
key={aLocation.id}
onClick={e => {
onListItemClick(index);
}}
>
{aLocation.text}
</li>
))}
</ul>
</div>
);

class App extends Component {
state = {
center: [51.505, -0.091],
zoom: 1,
markerIndex: 0
};

handleItemClick = index => {
console.log("show Marker for", listData[index]);
this.setState({
markerIndex: index
});
};

render() {
const markerItem = listData[this.state.markerIndex];
const MarkerToShow = <Marker position={[markerItem.lat, markerItem.lng]} />;
return (
<div>
<List onListItemClick={this.handleItemClick} />
<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"
/>
{MarkerToShow}
</Map>
</div>
);
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

您可以在这里找到工作代码:https://codesandbox.io/s/mm6nmw9z29

关于javascript - 如何以编程方式从另一个组件触发标记组件事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54878193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com