Ale*_*lls 3 javascript jquery backbone.js reactjs
我收到一个 React 错误:
错误:不变违规:_registerComponent(...):目标容器不是 DOM 元素。
我想我知道问题是什么,但我不知道如何解决它。问题是我想在渲染函数中引用一个 div 元素 id,但是当我想在那个 html 中添加一些东西时,渲染函数中的 html 还没有渲染到 DOM。所以我的问题是 - 在渲染到 DOM 之前,如何从渲染函数中引用 html 的元素 ID?这已成为我认为的 jQuery 问题。
这是一个简单的 Backbone.View 的渲染函数中的代码:
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?
);
Run Code Online (Sandbox Code Playgroud)
React.render
如果第一个调用本身有效。但是第二个 React.render 不起作用并且是抛出错误的那个。
我的模板看起来像这样:
<div>
<div id="react-menu-example-div-id">menu example goes here</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我的 Backbone.View 正在创建自己的 el。我想要做的可能完全是重击 - 我只想在同一个 Backbone 视图中渲染两个独立/不相关/不同的 React 组件。这有什么好的模式吗?
您在 self.el 中的第一个渲染语句是替换该元素的 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>
Run Code Online (Sandbox Code Playgroud)
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")
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1583 次 |
最近记录: |