You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Leaflet实现GeoJSON要素鼠标悬停变色的方法

React-Leaflet GeoJSON 鼠标悬停变色实现方案

当然有简洁的实现方式,利用 react-leaflet 的 GeoJSON 组件自带的事件绑定和动态样式属性就能搞定,不用复杂逻辑。直接看修改后的代码:

import { useState } from 'react';
import { MapContainer, GeoJSON, Popup, Tooltip } from 'react-leaflet';

// 定义基础样式和悬停样式
const baseStyle = {
  color: '#3388ff',
  weight: 2,
  opacity: 1
};

const hoverStyle = {
  color: '#ff6b6b',
  weight: 3,
  opacity: 1
};

export default function BaseMap({ places, features }) {
  // 跟踪当前悬停的要素ID
  const [hoveredFeatureId, setHoveredFeatureId] = useState(null);

  return (
    <MapContainer
      scrollWheelZoom={true}
      preferCanvas={true}
      renderer={bufferedRenderer}
    >
      {features.map((feature) => {
        const trailName = feature.properties.TRAIL_NAME_LOWER || "Trail Name";
        return (
          <GeoJSON
            key={feature.properties.fid}
            data={feature}
            // 根据悬停状态切换样式
            style={() => hoveredFeatureId === feature.properties.fid ? hoverStyle : baseStyle}
            // 鼠标悬停时记录当前要素ID
            onMouseOver={() => setHoveredFeatureId(feature.properties.fid)}
            // 鼠标移出时清空状态
            onMouseOut={() => setHoveredFeatureId(null)}
          >
            <Popup>
              <PopupInfo
                name={trailName}
                distance={feature.properties.TRAIL_LENGTH}
                id={feature.properties.fid}
              />
            </Popup>
            <Tooltip>{trailName}</Tooltip>
          </GeoJSON>
        );
      })}
      <LocationMarker />
    </MapContainer>
  );
}

核心逻辑说明

  • 通过 useState 维护当前悬停要素的唯一标识(这里用 feature.properties.fid,如果你的要素没有这个属性,换成其他唯一属性即可)
  • 给 GeoJSON 组件绑定 onMouseOver 和 onMouseOut 事件,触发时更新状态
  • style 属性根据当前状态动态返回基础样式或悬停样式,实现颜色切换

内容的提问来源于stack exchange,提问作者Trees4theForest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:15:34