简体   繁体   English

反应错误:目标容器不是 DOM 元素

[英]React Error: Target Container is not a DOM Element

I just got started using React so this is probably a very simple mistake, but here we go.我刚开始使用 React,所以这可能是一个非常简单的错误,但我们开始吧。 My html code is very simple:我的 html 代码非常简单:

<!-- base.html -->
<html>
  <head>
    <title>Note Cards</title>
    <script src="http://fb.me/react-0.11.2.js"></script>
<!--     <script src="http://fb.me/JSXTransformer-0.11.2.js"></script> -->
    <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
    {% load staticfiles %}
    <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
    <script src="{% static "build/react.js" %}"></script>
  </head>
  <body>
    <h1 id="content">Note Cards</h1>
    <div class="gotcha"></div>
  </body>
</html>

Note that I am using django's load static files here.请注意,我在这里使用 django 的加载静态文件。 My javascript is a bit more complex, so I won't post it all here unless someone requests it, but the line with the error is this:我的 javascript 有点复杂,所以除非有人要求,否则我不会在这里发布所有内容,但错误行是这样的:

React.renderComponent(
  CardBox({url: "/cards/?format=json", pollInterval: 2000}),
  document.getElementById("content")
);

After which I get the 'target container is not a DOM element error' yet it seems that document.getElementById("content") is almost certainly a DOM element.之后我得到“目标容器不是 DOM 元素错误”但似乎 document.getElementById("content") 几乎可以肯定是一个 DOM 元素。

I looked at this stackoverflow post, but it didn't seem to help in my situation.我查看了这个stackoverflow 帖子,但它似乎对我的情况没有帮助。

Anyone have any idea why I'd be getting that error?任何人都知道为什么我会收到那个错误?

I figured it out!我想到了!

After reading this blog post I realized that the placement of this line:阅读这篇博文后,我意识到这一行的位置:

<script src="{% static "build/react.js" %}"></script>

was wrong.错了。 That line needs to be the last line in the <body> section, right before the </body> tag.该行必须是<body>部分中的最后一行,就在</body>标记之前。 Moving the line down solves the problem.将线向下移动可以解决问题。

My explanation for this is that react was looking for the id in between the <head> tags, instead of in the <body> tags.我对此的解释是,react 正在寻找<head>标签之间的 id,而不是<body>标签。 Because of this it couldn't find the content id, and thus it wasn't a real DOM element.因此它找不到content ID,因此它不是真正的 DOM 元素。

Also make sure id set in index.html is same as the one you referring to in index.js还要确保在index.html 中设置的id与您在index.js 中引用的相同

index.html:索引.html:

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

index.js:索引.js:

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

Just to give an alternative solution, because it isn't mentioned.只是提供一个替代解决方案,因为它没有被提及。

It's perfectly fine to use the HTML attribute defer here.在这里使用 HTML 属性defer问题。 So when loading the DOM, a regular <script> will load when the DOM hits the script.因此,在加载 DOM 时,当 DOM 命中脚本时,将加载常规<script> But if we use defer , then the DOM and the script will load in parallel.但是如果我们使用defer ,那么 DOM脚本将并行加载。 The cool thing is the script gets evaluated in the end - when the DOM has loaded ( source ).很酷的事情是脚本最终会被评估 - 当 DOM 加载时( )。

<script src="{% static "build/react.js" %}" defer></script>

webpack solution网络包解决方案

If you got this error while working in React with webpack and HMR.如果您在 React 中使用 webpack 和 HMR 时遇到此错误。

You need to create template index.html and save it in src folder:您需要创建模板index.html并将其保存在src文件夹中:

<html>
    <body>
       <div id="root"></root>
    </body>
</html>

Now when we have template with id="root" we need to tell webpack to generate index.html which will mirror our index.html file.现在,当我们有id="root"模板时,我们需要告诉 webpack 生成 index.html,它将反映我们的index.html文件。

To do that:要做到这一点:

plugins: [
    new HtmlWebpackPlugin({
        title: "Application name",
        template: './src/index.html'
    })
],

template property will tell webpack how to build index.html file. template属性会告诉 webpack 如何构建index.html文件。

此外,将<script></script>到 html 文件底部的最佳实践也解决了这个问题。

I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html.我在 React 版本 16 中遇到了同样的错误。当尝试呈现 React 组件的 Javascript 包含在 html 中的静态父 dom 元素之前时,就会出现此错误。 Fix is same as the accepted answer, ie the JavaScript should get included only after the static parent dom element has been defined in the html.修复与接受的答案相同,即只有在 html 中定义了静态父 dom 元素后,才应包含 JavaScript。

Also you can do something like that:你也可以做这样的事情:

document.addEventListener("DOMContentLoaded", function(event) {
  React.renderComponent(
    CardBox({url: "/cards/?format=json", pollInterval: 2000}),
    document.getElementById("content")
  );
})

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. DOMContentLoaded事件在初始 HTML 文档完全加载和解析后触发,无需等待样式表、图像和子框架完成加载。

I got the same error i created the app with create-react-app but in /public/index.html also added matrialize script but there was to connection with "root" so i added我遇到了同样的错误,我用 create-react-app 创建了应用程序,但在 /public/index.html 中还添加了 matialize 脚本,但与“root”有连接,所以我添加了

<div id="root"></div>

just before就在之前

<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/ materialize.min.js"></script>

And it worked for me .它对我有用。

For those that implemented react js in some part of the website and encounter this issue.对于那些在网站的某些部分实现了 react js 并遇到此问题的人。 Just add a condition to check if the element exist on that page before you render the react component.在渲染反应组件之前,只需添加一个条件来检查该元素是否存在于该页面上。

<div id="element"></div>

...

const someElement = document.getElementById("element")
    
if(someElement) {
  ReactDOM.render(<Yourcomponent />, someElement)
}

One of the case I encountered the same error in a simple project.我在一个简单的项目中遇到相同错误的情况之一。 I hope the solution helps someone.我希望该解决方案可以帮助某人。

Below code snippets are sufficient to understand the solution :下面的代码片段足以理解解决方案:

index.html索引.html

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>

someFile.js : Notice the line const portalElement = document.getElementById("overlays"); someFile.js :注意行const portalElement = document.getElementById("overlays"); below :以下 :

const portalElement = document.getElementById("overlays");

const Modal = (props) => {
  return (
    <Fragment>
            {ReactDOM.createPortal(<Backdrop />, portalElement)}
            
      {ReactDOM.createPortal(
        <ModalOverlay>{props.children}</ModalOverlay>,
        portalElement
      )}
          
    </Fragment>
  );
};

I didn't have any element with id = "overlays" in my index.html file, so the highlighted line above was outputting null and so React wasn't able to find inside which element it should create the portal ie {ReactDOM.createPortal(<Backdrop />, portalElement) } so I got below error我的 index.html 文件中没有 id = "overlays" 的任何元素,因此上面突出显示的行输出 null,因此 React 无法在哪个元素中找到它应该创建门户的元素,即{ReactDOM.createPortal(<Backdrop />, portalElement) } 所以我得到以下错误

在此处输入图片说明

I added the div in index.html file and the error was gone.我在 index.html 文件中添加了 div 并且错误消失了。

 <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="overlays"></div>
    <div id="root"></div>
  </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM