问题
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