【发布时间】:2015-10-11 18:24:35
【问题描述】:
我收到一个 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?
);
第一个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).find('#react-menu-example-div-id')[0]吗? -
也许吧。明天试试。 jquery find 函数可以搜索不在 DOM 中的 HTML 吗?
-
虽然 jQuery 确实如此,但它仍然无法正常工作,正如 noveyak 在下面的答案中解释的那样。
-
@HannesJohansson 是的,谢谢。 jQuery 的 find() 函数似乎能够找到尚未在 DOM 中的 HTML 元素,我认为确实非常方便
标签: javascript jquery backbone.js reactjs