Possible to render react component within mapboxgl.Popup() in .setHTML or .setDOMContent?

二次信任 提交于 2019-12-11 04:57:27

问题


I am wondering if it is possible to render a react component within a mapboxgl.Popup(). Something like this:

    componentDidMount() {
            new mapboxgl.Popup()
            .setLngLat(coordinates)
            .setHTML(`<div>${<MapPopup />}<p>${moreText}</p></div>`)
            //.setDOMContent(`${<MapPopup />}`) ?????
            .addTo(this.props.mapboxMap)
    })

Or should this be done using ReactDOM.render?

ReactDOM.render(<MapPopup />, document.getElementById('root'))

This project will have buttons and inputs in the popup that connect to a redux store.

Thanks for any input!


回答1:


This works:

addPopup(el: JSX.Element, lat: number, lng: number) {
    const placeholder = document.createElement('div');
    ReactDOM.render(el, placeholder);

    const marker = new MapboxGl.Popup()
                        .setDOMContent(placeholder)
                        .setLngLat({lng: lng, lat: lat})
                        .addTo(map);
}

(Where I've used typescript to illustrate types, but you can just leave these out for pure js.) Use it as

addPopup(<h1>Losers of 1966 World Cup</h1>, 52.5, 13.4);



回答2:


I've been battling with this as well. One solution I found was using ReactDOM.render(). I created an empty popup then use the container generated by mapboxgl to render my React component.

    marker.setPopup(new mapboxgl.Popup({ offset: 18 }).setHTML(''));


     markerEl.addEventListener('mouseenter', () => {
        markerEl.classList.add('enlarge');

        if (!marker.getPopup().isOpen()) {
          marker.getPopup().addTo(this.getMap());

          ReactDOM.render(
            component,
            document.querySelector('.mapboxgl-popup-content')
          );
        }
      });


来源:https://stackoverflow.com/questions/48916901/possible-to-render-react-component-within-mapboxgl-popup-in-sethtml-or-setdo

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