React:了解导入语句

React: Understanding import statement

这两种说法有什么区别

import React from 'react';

import React, { Component } from 'react';

不应该 import React from 'react' 导入包括内容在内的所有内容吗?我应该读什么来理解这个?

import React, { Component } from 'react';

你可以做到

class Menu extends Component { /* ... */ } 

而不是

class Menu extends React.Component { /* ... */ } 

来自:

João Belo 发布了一个很好的答案供阅读,但我还要补充一件事。第二个实例是使用解构和 object-shorthand 从反应模块中获取 'Component' 属性 的值并将其分配给可以在本地使用的 'Component' 变量.如果你不知道解构和对象-shorthand,你一定要查一查。它们派上用场了。

您可以阅读此内容 here

不带大括号导入某些内容 会导入您要从中导入的模块中定义为default export 的任何内容。一个模块中只能有一个(或没有)默认导出。

foo.js:

const myObject = {foo: 'bar'};
export default myObject;

bar.js:

import theObject from './foo';

console.log(theObject);
// prints {foo: 'bar'}
// note that default exports are not named and can be imported with another name

使用花括号导入 导入模块使用该名称作为命名导出导出的内容。一个模块中可以有多个命名导出。

foo.js:

export const myObject = {foo: 'bar'};
export const anotherObject = {bar: 'baz'};

bar.js:

import {myObject, anotherObject, theObject} from './foo';

console.log(myObject);
// prints {foo: 'bar'}

console.log(anotherObject);
// prints {bar: 'baz'}

console.log(theObject);
// prints undefined
// because nothing named "theObject" was exported from foo.js

主要归结为导出变量的方式。我相信,这一定是 Facebook 贡献者深思熟虑的设计决定。

export default class ReactExample {}

export class ComponentExample {}
export class ComponentExampleTwo {}

在上面的示例中,ReactExample 可以不使用 {} 导入,而对于 ComponentExample,ComponentExampleTwo,您必须使用 {} 语句导入。

最好的理解方式是浏览源代码。

React export source code

React Component source code

import * as myCode from './../../myCode';

这会将 myCode 插入到当前作用域中,其中包含 来自 ./../../myCode.

文件中模块的所有导出
    import React, { Component } from 'react';

    class myComponent extends Component { ... }

通过使用上述语法,您的捆绑器(例如:webpack)仍将捆绑整个依赖项,但由于 Component 模块是以使用 { } 的方式导入到命名空间中的,我们可以只用 Component 而不是 React.Component 引用它。

有关详细信息,您可以阅读 mozilla ES6 module docs

这是ES6。

import Raect, { Component } from 'react';

喜欢

import default_export, { named_export } from 'react';

考虑两个文件。 Person.js 赞

const person = {
  name: 'johon doe'
}
export default person; // default export

Utility.js 喜欢

export const clean = () => { ... } //named export using const keyword
export const baseData = 10; //named export using const keyword

在 App.js 文件中导入。喜欢

import person from './Person';
import prs from './Person';

import {clean} from './Utility';
import {baseData} from './Utility';

import {data as baseData} from './Utility';
import {* as bundled} from './Utility';
//bundled.baseData
//bundled.clean