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

如何在react-google-maps/api的InfoWindow按钮点击时触发函数?

修复InfoWindow内按钮点击不触发函数的问题

问题根源

你的按钮onClick写法错误:onClick={reportPost(markerid)}会在InfoWindow渲染时立即执行reportPost函数,而不是等待点击事件。React渲染时会直接执行这个表达式,把函数返回值(此处为undefined)赋值给onClick,导致点击按钮时没有实际触发逻辑。

修复方案

将按钮的onClick改为箭头函数包裹,确保只有用户点击按钮时才调用reportPost:

<button onClick={() => reportPost(markerid)}>
  Report Post
</button>

完整修复后的组件代码

import { useState, useEffect, useCallback } from "react";
import {
  GoogleMap,
  useJsApiLoader,
  Marker,
  InfoWindow,
} from "@react-google-maps/api";
import Axios from "axios";

import markerIcon from "../images/markerIcon.png";

const containerStyle = {
  width: "100%",
  height: "100%",
};

const options = {
  mapId: process.env.MAP_ID,
  streetViewControl: false,
};

const center = {
  lat: 52.22611704066942,
  lng: 19.357910156250004,
};

function Map() {
  const [markers, setMarkers] = useState([]);

  useEffect(() => {
    Axios.get("http://localhost:3001/api/markers").then((response) => {
      setMarkers(response.data);
    });
  }, []);

  function reportPost(markerid) {
    console.log(markerid);
  }

  const { isLoaded } = useJsApiLoader({
    id: "google-map-script",
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
  });

  const onLoad = useCallback(function callback(map) {
    setMap(map);
  }, []);

  const onUnmount = useCallback(function callback(map) {
    setMap(null);
  }, []);

  const [map, setMap] = useState(null);

  const [activeMarker, setActiveMarker] = useState(null);

  const handleActiveMarker = (marker) => {
    setActiveMarker(marker);
  };

  return isLoaded ? (
    <div className="w-100 h-hero flex">
      <GoogleMap
        mapContainerStyle={containerStyle}
        options={options}
        center={center}
        zoom={6}
        onLoad={onLoad}
        onUnmount={onUnmount}
      >
        {markers.map(
          (
            { markerid, latitude, longitude, description },
            i,
            arr
          ) => {
            const position = {
              lat: latitude,
              lng: longitude,
            };

            return (
              <Marker
                key={markerid}
                icon={markerIcon}
                position={position}
                onClick={() => handleActiveMarker(markerid)}
              >
                {activeMarker === markerid ? (
                  <InfoWindow
                    onCloseClick={() => setActiveMarker(null)}
                  >
                      <div>
                          <div>
                            {description}
                          </div>
                        <div>
                          <button onClick={() => reportPost(markerid)}>
                            Report Post
                          </button>
                        </div>
                      </div>              
                  </InfoWindow>
                ) : null}
              </Marker>
            );
          }
        )}
      </GoogleMap>
    </div>
  ) : null;
}

export default Map;

补充说明

如果担心箭头函数每次渲染创建新函数(此处性能影响可以忽略),也可以用bind写法替代:

<button onClick={reportPost.bind(null, markerid)}>
  Report Post
</button>

两种写法效果一致,箭头函数的可读性更强,更适合日常开发场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:10:03