首页 > 解决方案 > 在 react-google-maps 中设置 OverlayView 的 z-index

问题描述

我正在使用react-google-maps并且我想完成类似于 Airbnb 的事情,当您将鼠标悬停在搜索结果上时,然后OverlayView在地图上突出显示“标记”(又名)。但是我要解决的问题是,如果 anOverlayView在 another 之下OverlayView,我想将“活动”OverlayView带到顶部(例如通过调整 z-index)。Airbnb 上的地图就是这样做的,当您将鼠标悬停在搜索结果上并检查标记时,它z-index会被更改为9001确保它被带到所有其他标记的前面。

几年前与此相关的一些问题尚未收到任何动静:

tomchentw/react-google-maps#199 tomchentw/react-google-maps#93

在 issue #199 中提到你可以绕过它this.refs.childDiv.parentNode并设置z-index它,但在 React v16this.refs中不再是我能说的东西(它已被弃用)。原始评论者附加了一个带有代码示例的jsfiddle ,它是:

class OverlayViewExample extends React.Component {
  render () {
    const pos = {lat: -34.397, lng: 150.644};
    const mapPane = OverlayView.OVERLAY_MOUSE_TARGET;
    const getOffset = this.getPixelPositionOffset.bind(this);

    return (
      <GoogleMap
        defaultZoom={8}
        defaultCenter={pos}
      >
        <OverlayView
          position={pos}
          mapPaneName={mapPane}
          getPixelPositionOffset={getOffset}
        >
          <div style={{zIndex: 2}} className="overlay" ref="childDiv">This should be in front</div>
        </OverlayView>

        <OverlayView
          position={pos}
          mapPaneName={mapPane}
          getPixelPositionOffset={getOffset}
        >
          <div style={{zIndex: 1}} className="overlay">Another overlay should be in front of me</div>
        </OverlayView>
      </GoogleMap>
    );
  }

  getPixelPositionOffset (width, height) {
    // this.refs is an empty object when I tried this :(
    if (this.refs.childDiv) {
        this.refs.childDiv.parentNode.style.zIndex = 2;
    }
    return { x: -(width / 2), y: -(height / 2) };
  }
}

当我尝试这种解决方法时,this.refs它是一个空对象,因此我无法更改该zIndex节点的底层。

是否有另一种方法可以确保当两个OverlayViews 彼此靠近时,我可以将背景中的一个带到前台?

标签: reactjsgoogle-mapsreact-google-maps

解决方案


这个问题的答案实际上是在我的问题中(我应该已经测试了来自 Github 的示例代码)......

在这条线上:实际上<div style={{zIndex: 2}} className="overlay" ref="childDiv">This should be in front</div>zIndex在做我想要的(它会在前景中提出我想要的任何元素)。

因此,在 eachOverlayView中,只需将 az-index应用于第一个子元素,这将影响 each 的排序OverlayView


推荐阅读