React.js:是否可以将react组件转换为HTML DOM? [英] 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
链接到另一个react组件中的特定方法(例如: _this.props.addList(位置)
).因此,我必须将以下代码行作为HTML DOM填充参数:
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 String
or HTML
. It's impossible for me to pass in String
as I have a button
that links to a specific method in another react component (something like: _this.props.addList(place)
). Thus I must fill the argument as HTML DOM as the following lines of code:
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组件,但似乎不起作用:
The codes work for me but I don't wanna create elements one by one. I've also tried to pass the argument with a React component but it seems not working:
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()
吗?
so is there another way to at least convert a react component to HTML so that I don't have to write document.createElement()
one by one?
谢谢
推荐答案
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);
});
},
这篇关于React.js:是否可以将react组件转换为HTML DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!