简体   繁体   English

单击 React-leaflet 中的标记时如何更改信息?

[英]How to change the information when clicking on a marker in React-leaflet?

I have a React-leaflet map on the left side with markers placed on it.我在左侧有一个 React 传单 map,上面放置了标记。 On the right side there is a list of point names.在右侧有一个点名称列表。 I need that when clicking on a certain marker, the name of the point that corresponds to the marker becomes 1st in the list.我需要在单击某个标记时,与该标记对应的点的名称成为列表中的第一个。 I take the coordinates of the points and the name of the places from the Firestore.我从 Firestore 中获取点的坐标和地点的名称。 How can I implement this behavior?我该如何实现这种行为? App.js:应用程序.js:

 function App() { const [selectedHouse, setSelectedHouse] = useState(); return ( <div className="App"> <Header /> <div className="map-content"> <Map onSelect={setSelectedHouse} /> <List selectedHouse={selectedHouse} /> </div> </div> ); }

Map.js: Map.js:

 const Map = ({ onSelect }) => { const [coordinates, setCoordinates] = useState([]); useEffect(() => { const q = query(collection(db, "map-markers")); onSnapshot(q, (querySnapshot) => { setCoordinates( querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); }, []); return ( <div style={{ width: "100%" }}> <MapContainer center={center} zoom={13} scrollWheelZoom={false} style={{ height: "100vh" }} > <TileLayer attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> {coordinates.map((coord, index) => ( <Marker key={index} eventHandlers={{ click: () => { onSelect(index); }, }} position={[parseFloat(coord.data.lat), parseFloat(coord.data.lon)]} icon={defaultIcon} /> ))} </MapContainer> </div> ); };

List.js:列表.js:

 const List = ({ selectedHouse }) => { const [houseTitles, setHouseTitle] = useState([]); useEffect(() => { const q = query(collection(db, "map-markers")); onSnapshot(q, (querySnapshot) => { setHouseTitle( querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); }, []); return ( <div style={{ width: "50%" }}> {houseTitles.filter((title, index) => index.== selectedHouse),map((title. index) => ( <ListItem key={index} title={title.data;title} /> ))} </div> ); };

在此处输入图像描述

In your List.js you need to add the selected house before the .map part so that the selected house properly appears:在您的List.js ,您需要在.map部分之前添加所选房屋,以便正确显示所选房屋:

    <div style={{ width: "50%" }}>
      {<ListItem title={houseTitles[selectedHouse]} />}
      {houseTitles
        .filter((title, index) => index !== selectedHouse)
        .map((title, index) => (
          <ListItem key={index} title={title.data.title} />
        ))}
    </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM