React.createElement: type is invalid -- expected a string (for built-in components) or a class/func

朴灿烈づ我的快乐病毒、 2022-12-02 10:44 280阅读 0赞

文章目录

    • 报错信息
    • ES6 模块导出及引入
    • CommonJS 模块导出及引入

报错信息

React运行报错:

在这里插入图片描述信息如下:

  1. Warning: React.createElement: type is invalid --
  2. expected a string (for built-in components) or a class/function (for composite components)
  3. but got: undefined. You likely forgot to export your component from the file it's defined in,
  4. or you might have mixed up default and named imports.

就是说:React在创建组件的时候,没有拿到值。
本来应该拿的的值是字符串(对内置组件而言),或者是class/function(对我们自定义的组件而言)。

出错原因:组件没有正确引入
可能性有很多,如:
- 被引用的组件没有导出(如忘记写export default)
- 被引用的组件导出了,但导出语法不正确
- 引入该组件时语法出错(引入模块时,需要视该模块的导出物的类型而定,)
依次检查,修改即可。

ES6 模块导出及引入

ES6模块导出引入标准写法:

  1. 只导出一个(方法,类,对象等)

    // Foo.js
    export default class Foo { }

    // Bar.js
    import Foo from ‘./Foo’

  2. 导出多个

    // Foo.js
    export class A { }
    export class B { }

    // Bar.js
    import { A, B } from ‘./Foo’

可以是类class,或方法function,或对象{ a: xxx, b: x xx }
但要注意导出物和引入时的对接

如:
导出 { name: '张三'. age: 22 },但是引入时:import name from xxx就会报错,
而应该是import { name } from xxx,或

  1. import aaa from xxx;
  2. var theName = aaa.name;
  3. var theAge = aaa.age;

CommonJS 模块导出及引入

而CommonJS的模块导出,引入的标准写法为:

  1. // Foo.js
  2. module.exports = xxx; // xxx可为单个变量,方法名,类名,或包含多个属性的对象
  3. // Bar.js
  4. const aaa = require("./Foo"); // aaa接到的就是赋值给 module.exports 的xxx

值传递方向:xxx 赋值到 module.exports 赋值到 aaa
其中aaa是自定义的变量名。

发表评论

表情:
评论列表 (有 0 条评论,280人围观)

还没有评论,来说两句吧...

相关阅读