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

React使用Google Map API时withScriptjs未导出错误求助

问题:React项目中withScriptjs导出找不到错误

复制相关代码到本地React项目后,持续出现以下错误:

export 'withScriptjs' (imported as 'withScriptjs') was not found in 'react-google-maps' (possible exports: Circle, DirectionsRenderer, FusionTablesLayer, GoogleMap, InfoWindow, KmlLayer, Marker, OverlayView, Polygon, Polyline, Rectangle, StreetViewPanorama, TrafficLayer, __esModule, withGoogleMap)

相关代码与配置

MyParentComponentWrapper.js

import React from "react";
import { compose, withProps, lifecycle } from "recompose";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from "react-google-maps";

const MyMapComponent = compose(
  withProps({
    googleMapURL:
      "https://maps.googleapis.com/maps/api/js?key=API_KEY=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  lifecycle({
    componentWillMount() {
      const refs = {};

      this.setState({
        position: null,
        onMarkerMounted: (ref) => {
          refs.marker = ref;
        },

        onPositionChanged: () => {
          const position = refs.marker.getPosition();
          console.log(position.toString());
        },
      });
    },
  }),
  withScriptjs,
  withGoogleMap
)((props) => (
  <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
    {props.isMarkerShown && (
      <Marker
        position={{ lat: -34.397, lng: 150.644 }}
        draggable={true}
        ref={props.onMarkerMounted}
        onPositionChanged={props.onPositionChanged}
      />
    )}
  </GoogleMap>
));

class MyParentComponentWrapper extends React.PureComponent {
  state = {
    isMarkerShown: false,
  };

  render() {
    return (
      <div>
        <MyMapComponent isMarkerShown={true} />
      </div>
    );
  }
}

export default MyParentComponentWrapper;

App.js

// import logo from './logo.svg';
import "./App.css";
import MyParentComponentWrapper from "./MyParentComponentWrapper";

function App() {
  return (
    <>
      <MyParentComponentWrapper />
    </>
  );
}

export default App;

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
    
  </body>
</html>

package.json

{
  "name": "map",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@react-google-maps/api": "^2.17.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

问题原因与解决方案

原因

你安装的是新版官方包@react-google-maps/api,但代码里调用的是旧版react-google-maps的API,两个包的导出结构完全不同。旧版的withScriptjs等高阶组件在新版中已被移除,改用组件式的加载方式。

解决方案

修改代码适配@react-google-maps/api的写法,同时移除不再需要的recompose依赖(新版推荐用React Hooks替代):

  1. 卸载recompose(如果已安装):
npm uninstall recompose
  1. 修改MyParentComponentWrapper.js为以下内容:
import React, { useState, useRef } from "react";
import { LoadScript, GoogleMap, Marker } from "@react-google-maps/api";

const mapContainerStyle = {
  height: "400px",
  width: "100%"
};

const defaultCenter = {
  lat: -34.397,
  lng: 150.644
};

const MyMapComponent = () => {
  const [markerPosition, setMarkerPosition] = useState(defaultCenter);
  const markerRef = useRef(null);

  const onMarkerDragEnd = () => {
    if (markerRef.current) {
      const position = markerRef.current.getPosition();
      const newPosition = { lat: position.lat(), lng: position.lng() };
      setMarkerPosition(newPosition);
      console.log(`标记位置:${JSON.stringify(newPosition)}`);
    }
  };

  return (
    <LoadScript
      googleMapsApiKey="你的Google Maps API密钥"
      libraries={["geometry", "drawing", "places"]}
    >
      <GoogleMap
        mapContainerStyle={mapContainerStyle}
        zoom={8}
        center={defaultCenter}
      >
        <Marker
          position={markerPosition}
          draggable={true}
          ref={markerRef}
          onDragEnd={onMarkerDragEnd}
        />
      </GoogleMap>
    </LoadScript>
  );
};

const MyParentComponentWrapper = () => {
  return (
    <div>
      <MyMapComponent />
    </div>
  );
};

export default MyParentComponentWrapper;
  1. 将代码中的你的Google Maps API密钥替换为实际密钥,确保该密钥已启用Google Maps JavaScript API。

修改后即可正常运行,实现拖拽标记获取位置的功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:40:37