MapBox can't add react component on markers popup

末鹿安然 提交于 2020-12-13 04:43:56

问题


I have been working on a Real Estate project and I've got stuck on adding a reactcomponent inside a markers popup. The image below shows the example of how the popup should look like: Popup example

This is the code where I am trying to add the popup on the marker:

var card = <Card />
var popup = new mapboxgl.Popup({ offset: 25 })
.setDOMContent(ReactDOM.render(card, document.getElementById('map')))

var marker = new mapboxgl.Marker(el)
.setLngLat(coordinates)
.setPopup(popup)
.addTo(map);
setMarkers(markers => [...markers, marker])

I keep getting the same error:

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

Please help me!


回答1:


The expected argument type of setDOMContent is Node, but the return type of ReactDOM.render is Component.
https://reactjs.org/docs/react-dom.html#render
https://docs.mapbox.com/mapbox-gl-js/api/markers/#popup#setdomcontent

In React, use React.useRef and .current to refer dom content.
https://reactjs.org/docs/hooks-reference.html#useref

const popupRef = React.useRef(null);
const popup = new mapboxgl.Popup({ offset: 25 })
  .setDOMContent(popupRef.current);

return (
  <>
    <div id="map"></div>
    <div ref={popupRef}>popup</div>
  </>
);


来源:https://stackoverflow.com/questions/64666141/mapbox-cant-add-react-component-on-markers-popup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!