如何为MarkerWithLabel Children元素设置onClick函数?

时间:2019-07-12 18:33:45

标签: react-google-maps

我无法为MarkerWithLabel子元素设置onClick函数。

我想创建一个MarkerWithLabel来显示一个简单的Component,一个具有几个h1元素的div,我想在用户单击任何h1元素时记录不同的内容,例如,如果用户单击h1,则记录“ 1”,h2“ 2”等...

我只能将onClick事件附加到MarkerWithLabel组件,而不附加到其子组件。

import React, { useState, useMemo, useEffect, useRef } from 'react';
import { compose, withProps } from 'recompose';
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from 'react-google-maps';
import { MarkerWithLabel } from 'react-google-maps/lib/components/addons/MarkerWithLabel';

import classes from './map.module.scss';

const loger = () => console.log('test');

const MyMapComponent = compose(
  withProps({
    googleMapURL:
      'https://maps.googleapis.com/maps/api/js?key=**YourApiKey**&libraries=drawing',
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div className={classes.test} />,
    mapElement: <div className={classes.subtest} />,
  }),
  withScriptjs,
  withGoogleMap
)(({ isMarkerShown, onMarkerClick }) => {
  const header = useRef();

  return (
    <GoogleMap
      defaultZoom={15}
      defaultCenter={{ lat: -34.5877058, lng: -58.4354737 }}
    >
      <MarkerWithLabel
        position={{ lat: -34.5811123, lng: -58.4287612 }}
        labelAnchor={new google.maps.Point(0, 0)}
        clickable
        onClick={loger}
        zIndex={0}
        // onClick={() => console.log('test')}
        labelStyle={{
          backgroundColor: 'white',
          fontSize: '16px',
        }}
      >
        <div>
          <h1
            onClick={loger}
            style={{ backgroundColor: 'red', zIndex: '1000000' }}
            ref={header}
          >
            Test
          </h1>
          <h2>other</h2>
          <h2>other</h2>
          <h2>other</h2>
          <h2>other</h2>
          <h2>other</h2>
        </div>
      </MarkerWithLabel>
    </GoogleMap>
  );
});

const MyFancyComponent = () => {
  const [isMarkerShown, setisMarkerShown] = useState(false);

  const delayedShowMarker = () => {
    setTimeout(() => {
      setisMarkerShown(true);
    }, 1000);
  };

  const handleMarkerClick = () => {
    setisMarkerShown(false);
    // delayedShowMarker();
  };

  useEffect(() => {
    delayedShowMarker();
  }, []);

  return (
    <MyMapComponent
      isMarkerShown={isMarkerShown}
      onMarkerClick={handleMarkerClick}
    />
  );
};

export default MyFancyComponent;

将onClick事件函数附加到h1元素

0 个答案:

没有答案