[英]Stuffing React component in Backbone view
我收到了一個React錯誤:
錯誤:不變違規:_registerComponent(...):目標容器不是DOM元素。
我想我知道問題是什么,但我不知道如何解決它。 問題是我想在render函數中引用div元素id,但渲染函數中的html還沒有呈現給DOM,直到我想把東西粘在那個html上。 所以我的問題是 - 如何在渲染到DOM之前從我的渲染函數中引用html的元素id? 這已成為我認為是一個jQuery問題。
這是一個簡單的Backbone.View的render函數中的代碼:
var self = this;
var ret = EJS.render(template, {});
this.$el.html(ret); //nice, but hasn't been rendered to the DOM yet
React.render(
<TimerExample start={Date.now()} />,
self.el //this works no problemo
);
React.render(
<MenuExample items={ ['Home', 'Services', 'About', 'Contact us'] } />,
$('#react-menu-example-div-id')[0] //this is *not* working, what is the right call here, so that this view can coexist with the above React view?
);
如果它本身是第一個React.render
調用。 但第二個React.render不起作用,是拋出錯誤的那個。
我的模板看起來像這樣:
<div>
<div id="react-menu-example-div-id">menu example goes here</div>
</div>
我的Backbone.View正在創建自己的el。 我想要做的可能是完全打擊 - 我只想在同一個Backbone視圖中呈現兩個獨立/不相關/不同的React組件。 這有一個很好的模式嗎?
您在self.el中的第一個render語句正在替換該元素的DOM內容。 因此,當您進行第二次渲染調用時,#react-menu-example div不再存在。 您可以通過渲染到父級內的另一個元素來解決此問題。 雖然總的來說我認為最好在React中使用盡可能多的模板/渲染,而不是使用骨干視圖來進行太多的模板化。
以下是在同一骨干視圖中呈現兩個不同ID的示例
https://jsfiddle.net/sa4vvtjL/2/
模板
<div id="search_container">a</div>
<script type="text/template" id="search_template">
<div>
<div id="placeholder1"></div>
<div id="react-menu-example-div-id"></div>
</div>
</script>
JS
var Hello = React.createClass({
render: function(){
return (<div> {this.props.start} </div>)
}
});
var Hello2 = React.createClass({
render: function(){
return (<div> lala </div>)
}
});
var SearchView = Backbone.View.extend({
initialize: function () {
this.render();
},
render: function () {
var template = _.template($("#search_template").html(), {});
this.$el.html(template);
React.render(
<Hello start={Date.now()} />,
$('#placeholder1')[0]
);
React.render(
<Hello2 />,
$('#react-menu-example-div-id')[0]
);
}
});
var search_view = new SearchView({
el: $("#search_container")
});
實際上說是id為'react-menu-example-div-id'的元素還沒有出現在頁面上。
我可以觀察到你正在使用jquery,為什么不呢:
$(document).ready(function() {
React.render(
<MenuExample items={ ['Home', 'Services', 'About', 'Contact us'] } />,
$('#react-menu-example-div-id')[0]
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.