简体   繁体   English

多个 ReactDOM.render() 抛出错误 Target container is not a DOM element

[英]Multiple ReactDOM.render() throwing error Target container is not a DOM element

Trying to integrate React into a non-React project, so I need to able to render the react apps at multiple elements.尝试将 React 集成到非 React 项目中,因此我需要能够在多个元素上呈现 React 应用程序。

Here's the index.js:这是 index.js:

import React from 'react';
import ReactDOM from 'react-dom';

import Activation from './forms/Activation';
import EditButton from '../components/editButton';

ReactDOM.render(<EditButton></EditButton>, document.getElementById('edit-button'));
ReactDOM.render(<Activation></Activation>, document.getElementById('activate-form'));

I am getting this error :我收到此错误

_registerComponent(...): Target container is not a DOM element.

The first component, EditButton , does render successfully, but the second is unable too.第一个组件EditButton确实渲染成功,但第二个组件也无法渲染。 If I move Activation to the top, then Activation will be the only component that renders.如果我将Activation移动到顶部,那么Activation将是唯一呈现的组件。

Has anyone run into this issue?有人遇到过这个问题吗? Any advice or direction would be greatly appreciated.任何建议或方向将不胜感激。

EDIT:编辑:

Because existing app isn't a SPA, depending on the route that user was on ('/' or '/product', etc.) the DOM element specified didn't exist.由于现有应用不是 SPA,根据用户所在的路径(“/”或“/product”等),指定的 DOM 元素不存在。 Fixed with just an if statement using getElementById, and if true ReactDOM.render().修复了仅使用 getElementById 的 if 语句,如果为真 ReactDOM.render()。

Thanks!谢谢!

It is sometimes a good practice to make sure the DOM element exists:有时确保 DOM 元素存在是一个好习惯:

if ( document.getElementById('root') ) {

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

}

First of all, check if script finds the second element.首先,检查脚本是否找到第二个元素。 You can check it with something like this:你可以用这样的东西检查它:

console.log(document.getElementById('activate-form'))
console.log(document.getElementById('edit-button'))

Also, check if there is only one element with each id exists on the page.另外,检查页面上是否只存在一个具有每个 id 的元素。 And finally if this elements are not nested.最后如果这个元素没有嵌套。

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

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