【问题标题】:Display InfoWindow only when marker clicked in reactJS仅当在 reactJS 中单击标记时才显示 InfoWindow
【发布时间】:2020-11-13 01:37:54
【问题描述】:

我只想在点击时显示 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>
  );
}

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

【问题讨论】:

    标签: reactjs onclick infowindow use-state


    【解决方案1】:

    您似乎混淆了当前状态值和一个允许您在 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 }
    

    【讨论】:

    • 它有效。谢谢。我已经尝试像您之前所说的那样删除阵列,不知道为什么它现在可以工作。我想可能是因为我重新启动了所有内容,因为我在代码中更改的一些 UI 现在正在显示。奇怪..
    猜你喜欢
    • 1970-01-01
    • 2018-06-28
    • 2017-02-14
    • 1970-01-01
    • 2022-10-24
    • 2016-10-06
    • 2017-03-09
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多