ES6 导入语句中花括号的用途是什么? [英] What is use of curly braces in an ES6 import statement?

查看:40
本文介绍了ES6 导入语句中花括号的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以看到有两种不同的导入方式:

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?

推荐答案

嗯,你是否应该在括号内或不带括号内导入组件之间的区别在于导出 它.

Well, the difference between whether you should import your components within brackets or without it lies in the way you export it.

有两种类型的导出

  1. 默认导出
  2. 命名导出

一个组件可以有一个默认导出和零个或多个命名导出.

如果一个组件是默认导出,那么你需要在不带括号的情况下导入它.

If a component is a default export then you need to import it without brackets.

例如,

export default App;

导入为

import App from './path/to/App';

命名的导出可能是这样的

A named export could be like

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';

同样,在 reactreact-dom 的情况下,ReactReactDOM默认导出 分别,而例如 Componentreact 中的 named exportrender 是命名 export在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆