为什么 es6 react 组件仅适用于“导出默认值"? [英] Why es6 react component works only with "export default"?
问题描述
这个组件确实有效:
export class Template extends React.Component {使成为() {返回 (<div>组件
);}};导出默认模板;
如果我删除最后一行,则不起作用.
未捕获的类型错误:无法读取未定义的属性toUpperCase"
我想,我不明白 es6 语法中的某些东西.不是必须在没有符号默认"的情况下导出吗?
不使用 default
导出意味着它是命名导出".您可以在一个文件中拥有多个命名导出.所以如果你这样做,
类模板{}类另一个模板{}导出 { 模板,另一个模板 }
然后您必须使用它们的确切名称导入这些导出.因此,要在另一个文件中使用这些组件,您必须这样做,
从 './components/templates' 导入 {Template, AnotherTemplate}
或者,如果您像这样导出为 default
导出,
导出默认类模板{}
然后在另一个文件中导入默认导出而不使用 {}
,就像这样,
从'./components/templates'导入模板
每个文件只能有一个默认导出.在 React 中,从文件中导出一个组件是一种约定,并将其导出为默认导出.
您可以在导入时自由重命名默认导出,
从'./components/templates'导入TheTemplate
并且您可以同时导入默认导出和命名导出,
import Template,{AnotherTemplate} from './components/templates'
This component does work:
export class Template extends React.Component {
render() {
return (
<div> component </div>
);
}
};
export default Template;
If i remove last row, it doesn't work.
Uncaught TypeError: Cannot read property 'toUpperCase' of undefined
I guess, I don't understand something in es6 syntax. Isn't it have to export without sign "default"?
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
这篇关于为什么 es6 react 组件仅适用于“导出默认值"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!