简体   繁体   English

React 动态导入不加载类

[英]React dynamic import doesn't load classes

I am trying to import a React component dynamically, in order to render it inside an element.我正在尝试动态导入 React 组件,以便在元素内呈现它。 However, it doesn't work and throws an exception saying :但是,它不起作用并抛出异常说:

"Element type is invalid: Expected a string (for built in components) or a class/Function (for composite components) but got: undefined.You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports" “元素类型无效:需要字符串(对于内置组件)或类/函数(对于复合组件)但得到:未定义。您可能忘记从定义的文件中导出组件,或者您可能混淆了默认和命名导入”

Do you have any idea?你有什么主意吗?

This is how I have imported the component:这是我导入组件的方式:

       import('../assessment/assessmentContainer').then(x=>{
        ReactDOM.render(<x.AssessmentContainer />, document.getElementById('root'));
       });       

    } ``` 

And this is my component which is exported

import React, { Fragment } from 'react';

``` export default class AssessmentContainer extends React.Component{
    render(){
        return(
            <Fragment>
                {"Assessment!"}
            </Fragment>
        )
    }
} ```





You are exporting a default from your component.您正在从组件导出默认值。 You have the option of naming the export of your component or using the default in your import.您可以选择命名组件的导出或使用导入中的默认值。

import('../assessment/assessmentContainer').then(x=> {
    ReactDOM.render(<x.default/>, document.getElementById('root'));
}); 

Try this : https://codesandbox.io/s/pensive-darkness-vi3xe试试这个: https : //codesandbox.io/s/pensive-darkness-vi3xe

 import('../assessment/assessmentContainer').then(x=> {
      ReactDOM.render(<x.default.AssessmentContainer/>,
         document.getElementById('root'));
    });

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

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