React 中的这个导入导出组件模式有什么问题?
What is wrong with this import export component pattern in React?
在我应用程序的 React 组件库中,我有一个名为 Branch 的 UIC,它具有:
Brand.Logo
Brand.WordMark
Brand.WorkMarkLogo
Brand.Logo 和 Brand.WordMark 工作正常但 Brand.WorkMarkLogo 在故事书中输出以下错误:
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.
请看这里:https://codesandbox.io/s/hmfnu
我做错了什么?
在导出默认模式中,不使用大括号。
import {Brand} from "./Brand";
正确的代码。
import Brand from "./Brand";
只有在 'export' 模式中,使用花括号。
export const abc = () => {};
import {abc} from '...';
当您导入并将它们括在大括号中时,您导入的是 named export
,而不是 default export
。
在您的 brand/index.js
文件中,第 10 行:
export default Brand;
要在模块中导入默认导出,您必须省略大括号。
因此,在您的 root/index.js
文件中,将第 3 行更改为
import Brand from "./Brand";
或者,您可以选择不导出 brand/index.js
文件中的默认值,并更改将导出放在 class 前面,如下所示:
export class Brand extends React.Component {
static Logo = Logo;
static LogoWordMark = LogoWordMark;
}
使用此方法,您可以像在同一个 brand/index.js
文件中一样添加额外的 classes,方法是添加:
export class Brand2 extends React.Component {
static Logo2 = Logo2;
static LogoWordMark2 = LogoWordMark2;
}
然后您将能够导入两个命名导出,例如:https://codesandbox.io/s/react-example-955rf
在我应用程序的 React 组件库中,我有一个名为 Branch 的 UIC,它具有:
Brand.Logo
Brand.WordMark
Brand.WorkMarkLogo
Brand.Logo 和 Brand.WordMark 工作正常但 Brand.WorkMarkLogo 在故事书中输出以下错误:
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.
请看这里:https://codesandbox.io/s/hmfnu
我做错了什么?
在导出默认模式中,不使用大括号。
import {Brand} from "./Brand";
正确的代码。
import Brand from "./Brand";
只有在 'export' 模式中,使用花括号。
export const abc = () => {};
import {abc} from '...';
当您导入并将它们括在大括号中时,您导入的是 named export
,而不是 default export
。
在您的 brand/index.js
文件中,第 10 行:
export default Brand;
要在模块中导入默认导出,您必须省略大括号。
因此,在您的 root/index.js
文件中,将第 3 行更改为
import Brand from "./Brand";
或者,您可以选择不导出 brand/index.js
文件中的默认值,并更改将导出放在 class 前面,如下所示:
export class Brand extends React.Component {
static Logo = Logo;
static LogoWordMark = LogoWordMark;
}
使用此方法,您可以像在同一个 brand/index.js
文件中一样添加额外的 classes,方法是添加:
export class Brand2 extends React.Component {
static Logo2 = Logo2;
static LogoWordMark2 = LogoWordMark2;
}
然后您将能够导入两个命名导出,例如:https://codesandbox.io/s/react-example-955rf