Is it ok to use ReactDOMServer.renderToString in the browser in areas where React isn't directly managing the DOM?

前端 未结 3 1522
暖寄归人
暖寄归人 2020-12-25 10:29

I\'m working on an app using Leaflet (via react-leaflet). Leaflet directly manipulates the DOM. The react-leaflet library doesn\'t change that, it just gives you React compo

相关标签:
3条回答
  • 2020-12-25 10:51

    According to the new documentation: https://reactjs.org/docs/react-dom-server.html

    The following methods can be used in both the server and browser environments:

    • renderToString()
    • renderToStaticMarkup()
    0 讨论(0)
  • 2020-12-25 11:01

    As Thomas already said, yes, you can use renderToString on the client. Just to be clear though, you will need to import ReactDOMServer on the client, which may seem counter-intuitive but appears to be correct. Example (on the client):

    import React from 'react';
    import ReactDOMServer from 'react-dom/server';
    
    const MyComp = (props) => {
      const html = ReactDOMServer.renderToString(<div>{someFunc(props)}</div>);
      // do something with your html, then
      return <div dangerouslySetInnerHTML={{__html: html}}></div>;
    };
    
    0 讨论(0)
  • 2020-12-25 11:08

    I know it is too old question, but since it has not been answered I wanted to share my thoughts.

    I was using the same thing, renderToString, but as the documentation recommends not to use it on client-side, I achieved it in another way, by using the react-dom's render method to render the custom component into div

    var myDiv = document.createElement('div');
    
    ReactDOM.render(
      <MarkerContents data={this.props.data} />,
      myDiv
    );
    
    var myIcon = L.divIcon({ 
        iconSize: new L.Point(50, 50), 
        html: myDiv.innerHTML
    });
    
    0 讨论(0)
提交回复
热议问题