huiyan-fe / react-bmapgl

基于百度地图JavaScript GL版API封装的React组件库
http://huiyan.baidu.com/github/react-bmapgl/
MIT License
112 stars 19 forks source link

单击显示InfoWindow #22

Open chenjh356 opened 3 years ago

chenjh356 commented 3 years ago

您好,请问Marker组件的onClick事件如何设置为单击显示InfoWindow,在js中可以调用openInfoWindow,那在组件中怎么调用这个方法嘛?

lyh543 commented 1 year ago

我自己封装了一个 MarkerWithInfoWindow:

import React, { useState } from 'react';
import {
  Marker, InfoWindow,
} from 'react-bmapgl';

export type Props = {
  map: BMapGL.Map;
  position: BMap.Point;
  children?: React.ReactNode;
  markerProps?: Omit<React.ComponentProps<typeof Marker>, 'position' | 'map' >;
  infoWindowProps?: Omit<React.ComponentProps<typeof InfoWindow>, 'position' | 'map'>;
};

export default function MarkerWithInfo({
  map,
  position,
  children = undefined,
  markerProps = { icon: 'loc_red' },
  infoWindowProps = {},
}: Props) {
  const [showInfo, setShowInfo] = useState(false);

  return (
    <>
      <Marker
        map={map}
        position={position}
        onClick={() => setShowInfo(true)}
        {...markerProps}
      />
      <div style={visibility: showInfo ? 'visible' : 'hidden'}>
        {/* @ts-expect-error children doesn't exist on props */}
        <InfoWindow
          map={map}
          position={position}
          onClickclose={() => setShowInfo(false)}
          onClose={() => setShowInfo(false)}
          {...infoWindowProps}
        >
          <>{children}</>
        </InfoWindow>
      </div >
    </>
  );
}
chenjh356 commented 1 year ago

您好,您的邮件我已收到。我将尽快回复