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

隔离google-map-react组件,避免React应用全局字体样式被覆盖

解决google-map-react注入字体样式覆盖全局的问题

方法一:手动移除注入的标签

google-map-react会自动加载谷歌字体样式表,你可以在组件加载完成后,定位到对应标签并移除:

在你的MapGoogle组件的componentDidMount方法中添加处理逻辑:

componentDidMount() {
  this.loadAsyncData();
  // 延迟执行确保地图已完成link标签注入
  setTimeout(() => {
    const fontLink = document.querySelector('link[href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Google+Sans:400,500,700|Google+Sans+Text:400&lang=fr"]');
    if (fontLink) {
      fontLink.remove();
    }
  }, 1000);
}

注:延迟时间可根据实际加载速度调整,保证地图资源加载完成后再执行移除操作。

方法二:自定义谷歌地图样式,强制覆盖字体

通过谷歌地图的自定义样式规则,让地图内部文字使用你指定的全局字体,避免默认字体污染全局样式。在GoogleMapReact组件中添加options属性传入自定义样式:

// 自定义地图样式,覆盖默认字体配置
const mapOptions = {
  styles: [
    {
      featureType: "all",
      elementType: "labels.text.fill",
      stylers: [
        { fontFamily: "你的全局字体名称" },
        { color: "#你的文字默认颜色" }
      ]
    },
    {
      featureType: "all",
      elementType: "labels.text.stroke",
      stylers: [
        { fontFamily: "你的全局字体名称" }
      ]
    }
  ]
};

// 在render方法的GoogleMapReact组件中添加options
<GoogleMapReact
  bootstrapURLKeys={{ key: uiCustomization?.google_maps_key }}
  defaultCenter={center}
  defaultZoom={zoom}
  options={mapOptions}
>
  {this.renderMarkers()}
</GoogleMapReact>

这样地图内部文字会使用你指定的字体,同时可以通过提升全局样式优先级,抵消可能残留的字体注入影响。

方法三:替换为@react-google-maps/api组件

如果上述方法效果不理想,推荐使用@react-google-maps/api——这是谷歌官方支持的React地图封装组件,功能更灵活,不会自动注入额外字体样式表,完全不会干扰全局样式。

先安装依赖:

npm install @react-google-maps/api

修改你的组件代码示例:

import React from "react";
import PropTypes from "prop-types";
import { GoogleMap, LoadScript } from "@react-google-maps/api";
import { axiosApiBackend } from "variables/axiosConfigs";
import Typography from "@mui/material/Typography";
import CustomMarker from "views/Maps/CustomMarker";
import Box from "@mui/material/Box";
import styled from "@mui/styles/styled";
import { withUiCustomizationContext } from "context/UiCustomizationContext";

const CaptionBox = styled(Box)(() => ({
  position: "absolute",
  right: "70px",
  bottom: "20px",
  color: "white",
  textShadow:
    "-1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000",
  display: "flex",
  alignItems: "center",
}));

class MapGoogle extends React.Component {
  constructor(props) {
    super(props);
    this.BACKEND_URL = "/cl";
    this.TYPE_COLORS = ["LightSalmon", "Khaki", "PaleGreen"];

    this.state = {
      cl: [],
      center: { lat: 43.695547, lng: 7.257504 },
      zoom: 12,
    };
  }

  componentDidMount() {
    this.loadAsyncData();
  }

  loadAsyncData() {
    let params = {
      filters: ["presents"],
    };
    axiosApiBackend.get(this.BACKEND_URL, { params }).then((result) => {
      this.setState({ cl: result.data });
    });
  }

  renderMarkers = () => {
    return this.state.cl
      .filter((cl) => cl.lg)
      .map((cl) => (
        <CustomMarker
          key={cl.id}
          position={{ lat: cl.lg.lat, lng: cl.lg.lng }}
          text={cl.id + ""}
          disablelink={"/cl/detail/" + cl.id}
          color={this.TYPE_COLORS[cl.lg.cp.type]}
        />
      ));
  };

  render() {
    const { center, zoom } = this.state;
    const { uiCustomization } = this.props;

    return (
      <>
        <div style={{ height: "calc(100vh - 70px)", width: "100%" }}>
          <LoadScript googleMapsApiKey={uiCustomization?.google_maps_key}>
            <GoogleMap
              mapContainerStyle={{ height: "100%", width: "100%" }}
              center={center}
              zoom={zoom}
            >
              {this.renderMarkers()}
            </GoogleMap>
          </LoadScript>
          <CaptionBox>
            <CustomMarker color={this.TYPE_COLORS[0]} />
            <Typography>&nbsp;Test&nbsp;&nbsp;</Typography>
            <CustomMarker color={this.TYPE_COLORS[1]} />
            <Typography>&nbsp;test&nbsp;&nbsp;</Typography>
            <CustomMarker color={this.TYPE_COLORS[2]} />
            <Typography>&nbsp;test</Typography>
          </CaptionBox>
        </div>
      </>
    );
  }
}

MapGoogle.propTypes = {
  uiCustomization: PropTypes.object,
};

export default withUiCustomizationContext(MapGoogle);

该组件仅加载谷歌地图核心API,不会自动注入任何额外样式,完全兼容你的全局字体设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:46:23