不变违例:_registerComponent(...):目标容器不是DOM元素 [英] Invariant Violation: _registerComponent(...): Target container is not a DOM element
问题描述
未捕获错误:不变违规:_registerComponent(...):目标容器不是DOM元素。
这是我的代码:
/ ** @jsx React.DOM * /
'use strict';
var React = require('react');
var App = React.createClass({
render(){
return< h1> Yo< / h1> ;;
}
}) ;
React.renderComponent(< App />,document.body);
HTML:
code>< HTML>
< head>
< script src =/ bundle.js>< / script>
< / head>
< body>
< / body>
< / html>
这是什么意思?
执行时脚本时,文档
元素不可用,因为脚本
本身在头
中。虽然在 head
和脚本是一个有效的解决方案a / 28965157/458193>在 DOMContentLoaded
事件中呈现,更好的是将脚本
在正文的底部
和将根组件呈现到 div
之前它:
< html>
< head>
< / head>
< body>
< div id =root>< / div>
< script src =/ bundle.js>< / script>
< / body>
< / html>
并在代码中调用
React.render(< App />,document.getElementById('root'));
您应该始终呈现为嵌套的 div
而不是 body
。否则,各种第三方代码(Google Font Loader,浏览器插件,无论如何)都可以修改 body
DOM节点当React不期望它,并导致非常难以追踪和调试的奇怪错误。 详细了解此问题。
将底部的脚本
的好东西是,直到脚本加载才能阻止渲染,以防您添加React服务器呈现给您的项目。
I get this error after a making trivial React example page:
Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.
Here's my code:
/** @jsx React.DOM */
'use strict';
var React = require('react');
var App = React.createClass({
render() {
return <h1>Yo</h1>;
}
});
React.renderComponent(<App />, document.body);
HTML:
<html>
<head>
<script src="/bundle.js"></script>
</head>
<body>
</body>
</html>
What does this mean?
By the time script is executed, document
element is not available, because script
itself is in the head
. While it's a valid solution to keep script
in head
and render on DOMContentLoaded
event, it's even better to put your script
at the very bottom of the body
and render root component to a div
before it:
<html>
<head>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
</html>
and in your code, call
React.render(<App />, document.getElementById('root'));
You should always render to a nested div
instead of body
. Otherwise all sorts of third-party code (Google Font Loader, browser plugins, whatever) can modify the body
DOM node when React doesn't expect it, and cause weird errors that are very hard to trace and debug. Read more about this issue.
The nice thing about putting script
at the bottom is that it won't block rendering until script load in case you add React server rendering to your project.
这篇关于不变违例:_registerComponent(...):目标容器不是DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!