仅当在 reactJS 中单击标记时才显示 InfoWindow

Display InfoWindow only when marker clicked in reactJS

我只想在单击时显示信息窗口。

我正在使用 useState 来更新值,以检查是否单击标记以显示 InfoWindow,否则不显示 InfoWindow。

我的代码:

import React, { useState } from "react";
import {
  GoogleMap,
  useLoadScript,
  Marker,
  InfoWindow,
} from "@react-google-maps/api";
import "./App.css";
import mapStyles from "./mapStyles";

const mapContainerStyle = {
  width: "100%",
  height: "100vh",
};
const center = {
  lat: 51.103807,
  lng: 10.057477,
};

const options = {
  styles: mapStyles,
  mapTypeControl: false,
  fullscreenControl: false,
  streetViewControl: false,
};


export default function App() {
  const [setSState, sstate] = React.useState(null);

  const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_KEY,
    libraries,
  });

  if (loadError) return "error loading maps";
  if (!isLoaded) return "loading maps";

  return (
    <div>
      <h1>Find a dealer near you</h1>
      <GoogleMap
        mapContainerStyle={mapContainerStyle}
        zoom={6}
        center={{ lat: 50.985509, lng: 10.690508 }}
        options={options}
      >
        <Marker
          position={{ lat: 50.985509, lng: 10.690508 }}
          onClick={() => {
            sstate(center);
            console.log("marker clicked");
          }}
        ></Marker>
        { sstate[0] ?  (
        <InfoWindow
          position={{
            lat: 51.081753,
            lng: 13.696073,
          }}
        >
          <div>
            <h3>Some text</h3>
            <h4>Some text</h4>
            <p>Some text</p>
          </div>
        </InfoWindow>
        ): null}
      </GoogleMap>
    </div>
  );
}

当我单击标记时,信息窗口没有显示。我没有做什么和应该做什么?有没有不同的、简单的方法?

您似乎混淆了当前状态值和允许您在 Marker 处理程序中更新它的函数。您还将 center 对象分配给没有 center[0] 属性 的状态,您在渲染条件中使用了它。

尝试将 const [setSState, sstate] = React.useState(null); 替换为 const [marker, setMarker] = React.useState(null); 以明确说明。

Marker中的onClick改为

onClick={() => {
  setMarker(center);
  console.log("marker clicked");
}}

以及将 InfoWindow 渲染到

的地方
{ marker ? (
  <InfoWindow
    position={{
      lat: 51.081753,
      lng: 13.696073,
    }}
  >
    <div>
      <h3>Some text</h3>
      <h4>Some text</h4>
      <p>Some text</p>
    </div>
  </InfoWindow>
) : null }