React.js:是否可以将 React 组件转换为 HTML DOM?

IT技术 javascript reactjs
2021-05-22 04:29:07

我正在开发一个基于地图的应用程序,该应用程序使用 Google Map API 在 React.js 中创建标记及其信息窗口。The infowindow.setContent()only 接受 aStringHTML我不可能传入,String因为我有一个button链接到另一个 react 组件中的特定方法(例如:)_this.props.addList(place)因此,我必须将参数作为 HTML DOM 填充为以下代码行:

var div = document.createElement('div');
var title = document.createElement('h4');
title.innerHTML = place.name;

var btn = document.createElement('button');
btn.className = 'btn btn-danger btn-block';
btn.appendChild(document.createTextNode('I want to go here !!'));

div.appendChild(title).appendChild(btn);

google.maps.event.addListener(marker, 'click', function() {

  infowindow.setContent( div );
  infowindow.open(map, this);
});

btn.addEventListener('click', function() {
  _this.props.addList(place);
});

这些代码对我有用,但我不想一个一个地创建元素。我也试过用 React 组件传递参数,但它似乎不起作用:

createMarker: function() {
  
  /** Some other lines of code */

  var _this = this;

  google.maps.event.addListener(marker, 'click', function() {

    infowindow.setContent( _this._renderInfoWindow(place) );
    infowindow.open(map, _this);

  });

},

// my infowindow rendering method
_renderInfoWindow: function(place) {
  return(
    <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>
  )
},

那么有没有另一种方法至少将一个react组件转换为HTML,这样我就不必document.createElement()一个一个地写了?

谢谢

4个回答

您可以在分离的 DOM 节点中通过React.render. 因此,以下代码应该适合您。

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);

  });

},

你也可以使用 React 的 renderToString() 方法

_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>
  );
}

这应该适用于如图所示的简单组件。React.renderToString() 将只返回组件的 html。

对于较新版本的 React

import ReactDOMServer from "react-dom/server";

let html = ReactDOMServer.renderToString(<div>...</div>)

这应该呈现 HTML。

import ReactDOMServer from "react-dom/server";

const html = ReactDOMServer.renderToString(<div>...</div>)