2015-04-12 73 views
11

我正在使用基於地圖的應用程序,該應用程序使用Google Map API在React.js中創建標記及其信息窗口。 infowindow.setContent()只接受StringHTML。我不可能通過String,因爲我有一個button鏈接到另一個反應組件中的特定方法(如:_this.props.addList(place))。因此,我必須填寫的參數作爲HTML DOM爲下面的代碼行:React.js:是否可以將反應組件轉換爲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); 
 
});

的代碼爲我工作,但一個我不想創建元素之一。我也試圖通過與陣營成分的說法,但似乎不工作:

​​

所以是有另一種方式來至少轉換反應成分爲HTML,讓我不要不必一一寫下document.createElement()

感謝

回答

15

您可以通過React.render呈現一種超然的DOM節點上ReactElement。因此,下面的代碼應該適合你。

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

我收到以下錯誤:「未捕獲的錯誤:不變衝突:React.render():無效的組件元素。」當應用您的解決方案 –

+0

得到了解決方案,對不起。這是因爲代碼在創建元素之前運行React.remder()。這裏是解決方案:var div = document.createElement('div'); \t \t \t的setInterval(函數(){ \t \t \t \t如果(DIV) \t \t \t \t \t clearInterval(); \t \t \t},5); \t \t \t React.render(_this._renderInfoWindow(place),div); –

+0

不會'_this'出現在沒有'var'的全局範圍之前嗎?這是打算嗎? – wprl

6

你也可以使用陣營的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。

+3

我用'react-dom/server'和'ReactDOMServer.renderToStaticMarkup'導入ReactDOMServer' – aceofspades

+0

按鈕事件處理程序不能使用這種方法。 –

0
// 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; 
相關問題