我正在使用react map GL,我想显示被点击的国家的名称(我只需要其他用途的名称). 目前,我有这样的代码:

import React, { useCallback, useMemo, useState } from "react";
import Map, {
  Marker,
  NavigationControl,
  FullscreenControl,
  ScaleControl,
  GeolocateControl,
  Source,
  Layer,
} from "react-map-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import Pin from "../../atoms/Pin/Pin";
import "./Map.scss";
import CITIES from "./cities";
import { useNavigate } from "react-router";

const MapNew = () => {
  const navigate = useNavigate();
  const [hoveredCountry, setHoveredCountry] = useState(null);
  const [cursor, setCursor] = useState<string>("auto");

  const onClick = useCallback((event) => {
    const feature = event.features && event.features[0];
    if (feature) {
      const countryName = feature.properties.name;
      window.alert(`Clicked on ${countryName}`);
    }
  }, []);

  const pins = useMemo(
    () =>
      CITIES.map((city, index) => (
        <Marker
          key={`marker-${index}`}
          longitude={city.longitude}
          latitude={city.latitude}
          anchor="bottom"
        >
          <Pin />
        </Marker>
      )),
    []
  );

  const geojsonUrl =
    "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_admin_0_countries.geojson";

  const sourceId = "countries";
  const layerId = "country-fills";

  return (
    <div className="map-parent-wrapper">
      <Map
        initialViewState={{
          latitude: 51.1657,
          longitude: 10.4515,
          zoom: 3,
          bearing: 0,
          pitch: 0,
        }}
        mapStyle="mapbox://styles/mapbox/navigation-day-v1"
        mapboxAccessToken=""
        scrollZoom={false}
        onClick={onClick}
        cursor={cursor}
      >
        <GeolocateControl position="top-left" />
        <FullscreenControl position="top-left" />
        <NavigationControl position="top-left" />
        <ScaleControl />

        <Source id={sourceId} type="geojson" data={geojsonUrl}>
          <Layer
            id={layerId}
            type="fill"
            source={sourceId}
            paint={{
              "fill-color": [
                "case",
                ["==", ["get", "name"], "Austria"],
                "blue", // Color for Austria
                ["==", ["get", "name"], "Croatia"],
                "green", // Color for Croatia
                "gray", // Default color
              ],
              "fill-opacity": 0.5,
            }}
          />
        </Source>

        {pins}
      </Map>
    </div>
  );
};

export default MapNew;

无论我做什么,我都不能访问名称onClick,即使上色的逻辑有效:

enter image description here

所以,我希望当我点击一个有色人种的国家时,我会得到它的名字.

推荐答案

您可以这样做:

  1. 为 map 添加引用

const mapRef = useRef(null);

  1. 添加使用Geojson数据(并返回点击的国家名称)的onClick函数:
 const onClick = useCallback(async (event) => {
    console.log(mapRef);
    const map = mapRef.current.getMap();
    const features = await map.queryRenderedFeatures(event.point, {
      layers: [layerId],
    });

    if (features.length > 0) {
      const clickedCountryName = features[0].properties.name;
      console.log(`clicked: ${clickedCountryName}`);
      navigate(`/${clickedCountryName}`);
    }
  }, []);
  1. 添加REF和onClick到 map :
<Map
    initialViewState={{
        latitude: 51.1657,
        longitude: 10.4515,
        zoom: 3,
        bearing: 0,
        pitch: 0,
    }}
    mapStyle="mapbox://styles/mapbox/navigation-day-v1"
    mapboxAccessToken=""
    scrollZoom={false}
    onClick={onClick}
    cursor={cursor}
    ref={mapRef} // add this
>

Reactjs相关问答推荐

从app.js导航,这是在BrowserRouter包装之外

从`redux—thunk`导入thunk `在stackblitz中不起作用

避风港访问端口以包含Reaction应用程序

为什么登录错误和密码在创建Reaction-Hook-Form后立即被删除?

React组件未出现

如何在MUI x图表条形图上放置圆角?

在react上隐藏源映射

太多的重新渲染 - React 中的无限循环.如何使用React.effect并使用fetch?

React 应用程序可以嵌入到 PowerPoint 中吗?

如何使用 redux 和 react-plotly.js

需要先填写依赖输入字段,以便其他人工作

位于组件material-ui中的TextField中的 map 功能不起作用

在 React 中将路径与查询变量匹配

使用 React.lazy 调试 webpack 代码拆分

React Final Form - 单选按钮在 FieldArray 中不起作用

从一个获取 axios 请求(ReactJS)中删除默认参数

如何跨微前端 React 应用管理状态管理?

如何在 react-router-dom v6 中实现监听功能?

下拉菜单在 AppBar 中未正确对齐

点击提交后自动添加#