不变冲突:_registerComponent(…):目标容器不是DOM元素

我做了一个微不足道的反应示例页面后,我得到这个错误:

未捕获错误:不变冲突:_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:

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

这是什么意思?

在执行脚本的时候, document元素还不可用,因为script本身在head 。 虽然这是保持scriptDOMContentLoaded事件上呈现的有效解决scheme,但script放在body底部并将根组件呈现为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,浏览器插件,无论什么)都可以在React不期望的时候修改body DOM节点,并导致很难跟踪和debugging的奇怪错误。 阅读更多关于这个问题。

script放在底部的好处在于,在将脚本文件添加到项目中之前,它不会阻止渲染,直到脚本加载。

/index.html

 <!doctype html> <html> <head> <title>My Application</title> <!-- load application bundle asynchronously --> <script async src="/app.js"></script> <style type="text/css"> /* pre-rendered critical path CSS (see isomorphic-style-loader) */ </style> </head> <body> <div id="app"> <!-- pre-rendered markup of your JavaScript app (see isomorphic apps) --> </div> </body> </html> 

/app.js

 import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; function run() { ReactDOM.render(<App />, document.getElementById('app')); } const loadedStates = ['complete', 'loaded', 'interactive']; if (loadedStates.includes(document.readyState) && document.body) { run(); } else { window.addEventListener('DOMContentLoaded', run, false); } 

(IE9 +)

注意 :在头文件中使用<script async src="..."></script>可确保浏览器加载HTML内容之前开始下载JavaScript包。

来源: React初学者工具包 , 同构样式加载器

ready函数可以像这样使用:

 $(document).ready(function () { React.render(<App />, document.body); }); 

如果你不想使用jQuery,你可以使用onload函数:

 <body onload="initReact()">...</body> 

只是一个疯狂的猜测,如何添加到index.html如下:

 type="javascript" 

喜欢这个:

 <script type="javascript" src="public/bundle.js"> </script> 

对我来说,它的工作! 🙂

在我的情况下,这个错误是由热重新加载,而引入新的类。 在项目的这个阶段,使用普通的观察者来编译你的代码。

对于那些使用ReactJS.Net并在发布后出现此错误:

检查.jsx文件的属性,并确保“ Build Action设置为“ Content 。 那些设置为None将不会被发布。 我从这个答案中find了这个解决scheme。

我遇到了类似/相同的错误消息。 在我的情况下,我没有定义渲染ReactJS组件的目标DOM节点。 确保使用适当的“id”或“name”以及其他HTML属性(适合您的devise需要)来定义HTML目标节点,