繁体   English   中英

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

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

我在左侧有一个 React 传单 map,上面放置了标记。 在右侧有一个点名称列表。 我需要在单击某个标记时,与该标记对应的点的名称成为列表中的第一个。 我从 Firestore 中获取点的坐标和地点的名称。 我该如何实现这种行为? 应用程序.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:

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

列表.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> ); };

在此处输入图像描述

在您的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