不变违规:_registerComponent(...):目标容器不是 DOM 元素 [英] Invariant Violation: _registerComponent(...): Target container is not a DOM element

查看:27
本文介绍了不变违规:_registerComponent(...):目标容器不是 DOM 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在制作一个简单的 React 示例页面后收到此错误:

I get this error after a making trivial React example page:

未捕获的错误:不变违规:_registerComponent(...):目标容器不是 DOM 元素.

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

这是我的代码:

/** @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>

这是什么意思?

推荐答案

到脚本执行时,document 元素还不可用,因为 script 本身在头部.虽然将 script 保留在 head 上渲染是一种有效的解决方案DOMContentLoaded 事件,最好将 script 放在 body and 的最底部像这样将根组件渲染到 div 之前:

By the time script is executed, document element is not available yet, 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 like this:

<html>
<head>
</head>
<body>
  <div id="root"></div>
  <script src="/bundle.js"></script>
</body>
</html>

bundle.js 中,调用:

React.render(<App />, document.getElementById('root'));

您应该始终渲染到嵌套的 div 而不是 body. 否则,各种第三方代码(Google Font Loader、浏览器插件等)可以在 React 不期望它时修改 body DOM 节点,并导致很难跟踪和调试的奇怪错误.阅读有关此问题的更多信息.

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.

script 放在底部的好处是它不会在脚本加载之前阻止渲染,以防万一您将 React 服务器渲染添加到您的项目中.

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.

React.render 已弃用,使用 ReactDOM.render相反.

React.render is deprecated, use ReactDOM.render instead.

示例:

import ReactDOM from 'react-dom';

ReactDOM.render(<App />, document.getElementById('root'));

这篇关于不变违规:_registerComponent(...):目标容器不是 DOM 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆