React.createElement: type is invalid -- expected a string (for built-in components) or a class/func
文章目录
- 报错信息
- ES6 模块导出及引入
- CommonJS 模块导出及引入
报错信息
React运行报错:
信息如下:
Warning: React.createElement: 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.
就是说:React在创建组件的时候,没有拿到值。
本来应该拿的的值是字符串(对内置组件而言),或者是class/function(对我们自定义的组件而言)。
出错原因:组件没有正确引入
可能性有很多,如:
- 被引用的组件没有导出(如忘记写export default
)
- 被引用的组件导出了,但导出语法不正确
- 引入该组件时语法出错(引入模块时,需要视该模块的导出物的类型而定,)
依次检查,修改即可。
ES6 模块导出及引入
ES6模块导出引入标准写法:
只导出一个(方法,类,对象等)
// Foo.js
export default class Foo { }// Bar.js
import Foo from ‘./Foo’导出多个
// 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
,或
import aaa from xxx;
var theName = aaa.name;
var theAge = aaa.age;
CommonJS 模块导出及引入
而CommonJS的模块导出,引入的标准写法为:
// Foo.js
module.exports = xxx; // xxx可为单个变量,方法名,类名,或包含多个属性的对象
// Bar.js
const aaa = require("./Foo"); // aaa接到的就是赋值给 module.exports 的xxx
值传递方向:xxx
赋值到 module.exports
赋值到 aaa
其中aaa是自定义的变量名。
还没有评论,来说两句吧...