我收到一个 React 错误:
Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.
我想我知道问题是什么,但我不知道如何解决。问题是我想在 render 函数中引用一个 div 元素 id,但是在我想将某些内容粘贴到该 html 中时,render 函数中的 html 尚未呈现给 DOM。所以我的问题是——在将 html 呈现给 DOM 之前,我如何从我的呈现函数中引用它的元素 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?
);
第一个 React.render
调用在它自己的情况下有效。但是第二个 React.render 不起作用,并且是抛出错误的那个。
我的模板是这样的:
<div>
<div id="react-menu-example-div-id">menu example goes here</div>
</div>
我的 Backbone.View 正在创建自己的 el。我正在尝试做的事情可能完全是一团糟——我只想在同一个 Backbone View 中呈现两个独立/不相关/不同的 React 组件。有好的模式吗?
最佳答案
您在 self.el 中的第一个渲染语句正在替换该元素的 DOM 内容。因此,当您进行第二次渲染调用时,#react-menu-example div 已不存在。您可以通过渲染到父元素中的另一个元素来解决这个问题。尽管总的来说,我认为最好在 React 中拥有尽可能多的模板/渲染,而不是将主干 View 用于过多的模板。
这是在同一个主干 View 中渲染到两个不同 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")
});
关于javascript - 在 Backbone View 中填充 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31553621/