我编写了这个包装器组件,它在整个地图上放置了一个<Rectangle/>,以阻止点击传递到下面的地图。同时仍然允许您单击 <infoBox/> 内的内容。
这允许将enableEventPropagation 设置为true 而不会产生问题。然后我使用mouseOver 和mouseOut 来控制矩形的工作方式。就我而言,我使用单击矩形来关闭我的<InfoBox/>。您可以轻松地隐藏和显示它。
/* global google */
/* eslint-disable jsx-a11y/no-static-element-interactions */
import React from 'react';
import PropTypes from 'prop-types';
import { Rectangle } from 'react-google-maps';
import GoogleInfoBox from 'react-google-maps/lib/components/addons/InfoBox';
const cardWidth = 235;
const boxShadow = 25; // space for outer shadow
const iconHeight = 2; // the actual height is 48px but we use 6px instead to hide the icon but keep it's shadow
class InfoBox extends React.Component {
constructor(props) {
super(props);
this.closable = true;
}
onClose = () => {
if (this.closable) this.props.onClose();
}
onHover = () => {
this.closable = false;
}
onMouseOut = () => {
this.closable = true;
}
render() {
const { children, position, onClose, type } = this.props;
return (
<div className="info-box">
<Rectangle
options={{ fillColor: '#ffffff', fillOpacity: 0.7, zIndex: 100 }}
bounds={{ north: 90, south: -90, east: 180, west: -180 }}
onClick={this.onClose}
/>
<GoogleInfoBox
position={new google.maps.LatLng(position.lat, position.lng)}
onCloseClick={onClose}
options={{
alignBottom: true,
disableAutoPan: false,
pixelOffset: new google.maps.Size(-(cardWidth / 2) - boxShadow, -iconHeight),
maxWidth: width,
isHidden: false,
visible: true,
pane: 'floatPane',
enableEventPropagation: true,
}}
>
<div
onMouseOver={this.onHover}
onFocus={this.onHover}
onMouseOut={this.onMouseOut}
onBlur={this.onMouseOut}
>
{ children }
</div>
</GoogleInfoBox>
</div>
);
}
}
InfoBox.propTypes = {
children: PropTypes.element.isRequired,
position: PropTypes.shape({
lat: PropTypes.number.isRequired,
lng: PropTypes.number.isRequired,
}).isRequired,
onClose: PropTypes.func,
type: PropTypes.string,
};
export default InfoBox;