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



我只想在单击时显示infoWindow。

我使用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 [marker, setMarker] = React.useState(null);替换const [setSState, sstate] = 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 }

最新更新