[英]React.js: Is it possible to convert a react component to HTML DOM's?
我正在开发一个基于地图的应用程序,该应用程序使用Google Map API在React.js中创建标记及其信息窗口。 infowindow.setContent()
只接受String
或HTML
。 我无法传递String
因为我有一个链接到另一个反应组件中的特定方法的button
(类似于: _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()
吗?
谢谢
您可以通过React.render在分离的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>)
// 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.