簡體   English   中英

在 React 中渲染新組件 onclick

[英]Rendering new component onclick in React

我是 React 新手,正在做一個項目。 我正在使用 mapbox-gl 並嘗試在發生 hover 事件時呈現彈出窗口。 現在,如果我將坐標和描述記錄到控制台,它可以正常工作,但彈出窗口根本無法顯示。 當圖層懸停時,我還需要做些什么來渲染彈出組件嗎?

 popupClick(e: any) {
    var coordinates = e.features[0].geometry.coordinates.slice();
    var description = e.features[0].properties.description
    e.target._canvas.style.cursor = 'default';
      // Ensure that if the map is zoomed out such that multiple
    // copies of the feature are visible, the popup appears
    // over the copy being pointed to.
    while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
    coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
    }
    
    return (
      <Popup 
        coordinates={coordinates}
      >
          {description}
      </Popup>
    )

  }

<Layer
          id = 'markers'
          style = 'cursor-pointer'
          layout={{
            'icon-image': '{icon}-15',
            'icon-allow-overlap': true
          }}
          onMouseEnter = {this.popupClick}
          onMouseLeave = {this.popupLeave}
          sourceId='places'
  />

當您的 hover 事件發生時,您可以設置彈出窗口的可見性狀態。

 popupClick(e: any) {
    var coordinates = e.features[0].geometry.coordinates.slice();
    var description = e.features[0].properties.description
    e.target._canvas.style.cursor = 'default';
      // Ensure that if the map is zoomed out such that multiple
    // copies of the feature are visible, the popup appears
    // over the copy being pointed to.
    while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
    coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
    }

this.setState({showPopUp: true})
    }

然后在你的render()你可以做類似的事情

    <Layer
              id = 'markers'
              style = 'cursor-pointer'
              layout={{
                'icon-image': '{icon}-15',
                'icon-allow-overlap': true
              }}
              onMouseEnter = {this.popupClick}
              onMouseLeave = {this.popupLeave}
              sourceId='places'
      />
    showPopUp &&  
<Popup coordinates={coordinates} >
              {description}
          </Popup>

因此當 showPopUp 為 true 時,將顯示您的 Popup 元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM