在 react-google-maps 中设置 OverlayView 的 z-index

Set z-index of OverlayView in react-google-maps

我正在使用 react-google-maps,我想完成类似于 Airbnb 的操作,当您将鼠标悬停在搜索结果上时,"marker"(又名 OverlayView)会突出显示在地图。但我要解决的问题是,如果一个 OverlayView 在另一个 OverlayView 下面,我想把那个 "active" OverlayView 放到顶部(比如通过调整 z-指数)。 Airbnb 上的地图就是这样做的,当您将鼠标悬停在搜索结果上并检查标记时,z-index 会更改为 9001 以确保它位于所有其他标记的前面。

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

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

在 issue #199 中提到你可以使用 this.refs.childDiv.parentNode 绕过它并在其上设置 z-index,但在 React v16 中 this.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

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

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

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

所以在每个 OverlayView 中,只需将 z-index 应用于第一个子元素,这将影响每个 OverlayView.

的排序