ES6 导入语句中大括号的用途是什么? [英] What is use of curly braces in an ES6 import statement?
问题描述
我可以看到有两种不同的导入方式:
I can see there are two different ways to import:
import React from 'react'
import { render } from 'react-dom'
第二个有括号.两者有什么区别?什么时候应该加括号?
The second one has brackets. What is the difference between the two? And when should I add brackets?
推荐答案
嗯,你应该在括号内还是没有括号导入你的组件的区别在于你export
它.
Well, the difference between whether you should import your components within brackets or without it lies in the way you export
it.
有两种类型的导出
- 默认导出
- 命名导出
一个组件可以有一个默认导出和零个或多个命名导出.
如果一个组件是默认导出,那么你需要在不带括号的情况下导入它.
If a component is a default export then you need to import it without brackets.
例如,
export default App;
导入为
import App from './path/to/App';
命名导出可能类似于
export const A = 25;
或
export {MyComponent};
然后就可以导入了
import {A} from './path/to/A';
或
import {A as SomeName} from './path/to/A';
如果您的组件有一个默认导出和几个命名导出,您甚至可以在导入时将它们混合在一起
If your component has one default export and few named exports, you can even mix them together while importing
import App, {A as SomeName} from './path/to/file';
与react
和react-dom
类似,React
和ReactDOM
是默认导出
而,例如 Component
是 react
中的 named export
而 render
是命名导出在 react-dom
中.这就是你可以做的原因
Similarly in case of react
and react-dom
, React
and ReactDOM
are default exports
respectively whereas, for instance Component
is a named export
in react
and render
is a named export in react-dom
. That's the reason you can either do
import ReactDOM from 'react-dom';
然后使用
ReactDOM.render()
或者像您的问题中提到的那样使用它.
or use it like mentioned in your question.
这篇关于ES6 导入语句中大括号的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!