React.js: Is it possible to convert a react component to HTML DOM's?

后端 未结 5 492
孤城傲影
孤城傲影 2021-02-05 05:14

I\'m working on a map-based app that uses Google Map API to create markers and its info window in React.js. The infowindow.setContent() only accepts either a

相关标签:
5条回答
  • 2021-02-05 05:43

    For newer versions of React

    import ReactDOMServer from "react-dom/server";
    
    let html = ReactDOMServer.renderToString(<div>...</div>)
    
    0 讨论(0)
  • 2021-02-05 05:43
    // Create a DOM element to hold the react component.
    var span = document.createElement('span');
    // Render the React component.
    React.render(h.button(null, 'Buttonz!'), span);
    // This will give the result as a string, which is useful if you've escaped
    // React's context (e.g. inside DataTables).
    // Obviously, the component will no longer be reactive but this is a
    // good way to leverage simple stuff you've already written in React.
    // In my case, I'm primarily leveraging React wrappers around Bootstrap components.
    // The important thing is that componentDidMount gets called.
    return span.outerHTML;
    
    0 讨论(0)
  • 2021-02-05 05:56

    You can render a ReactElement in a detached DOM Node via React.render. Thus, the following code should work for you.

    createMarker: function() {
    
      /** Some other lines of code */
    
      _this = this;
    
      google.maps.event.addListener(marker, 'click', function() {
    
        var div = document.createElement('div');
        ReactDOM.render( _this._renderInfoWindow(place), div );
        infowindow.setContent( div );
        infowindow.open(map, this);
    
      });
    
    },
    
    0 讨论(0)
  • 2021-02-05 06:00

    This should render the HTML.

    import ReactDOMServer from "react-dom/server";
    
    const html = ReactDOMServer.renderToString(<div>...</div>)
    
    0 讨论(0)
  • 2021-02-05 06:01

    You could also use React's renderToString() method

    _renderInfoWindow: function(place) {
      return React.renderToString(
        <div>
          <h4>{place.name}</h4>
          <p>{place.cost}</p>
          <button className="btn btn-danger btn-block" onClick={this.props.addList.bind(this, place)}>I want to go here !! </button>
        </div>
      );
    }
    

    This should work for a simple component as shown. React.renderToString() will return only the html for the component.

    0 讨论(0)
提交回复
热议问题