【发布时间】:2018-04-14 00:07:22
【问题描述】:
这两种说法有什么区别
import React from 'react';
和
import React, { Component } from 'react';
不应该import React from 'react' 导入包括内容在内的所有内容?我应该阅读什么来理解这一点?
【问题讨论】:
标签: javascript reactjs
这两种说法有什么区别
import React from 'react';
和
import React, { Component } from 'react';
不应该import React from 'react' 导入包括内容在内的所有内容?我应该阅读什么来理解这一点?
【问题讨论】:
标签: javascript reactjs
你可以阅读这个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
【讨论】:
有
import React, { Component } from 'react';
你可以的
class Menu extends Component { /* ... */ }
而不是
class Menu extends React.Component { /* ... */ }
【讨论】:
Component 属性(以及 React 中的所有其他内容),它只是将解构的 Component 作为独立的变量也可以参考。
extends Component 而不是 extends React.Component 的另一个优点是,如果您将来出于某种原因决定将所有组件都包含在您的应用程序从自定义组件类扩展。但对于大多数应用来说,这可能不太可能。
这是 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
【讨论】:
João Belo 发布了一个很好的阅读答案,但我还要添加一件事。第二个实例是使用解构和对象简写从反应模块中获取“组件”属性的值,并将其分配给可以在本地使用的“组件”变量。如果您不了解解构和对象简写,您绝对应该查找它们。它们会派上用场。
【讨论】:
import { Foo as AliasToFoo } 与 const { Foo: AliasToFoo } = ...
这主要归结为您导出变量的方式。我相信,这一定是 Facebook 贡献者深思熟虑的设计决定。
export default class ReactExample {}
export class ComponentExample {}
export class ComponentExampleTwo {}
在上面的例子中,ReactExample 可以不使用 {} 导入,而 ComponentExample, ComponentExampleTwo 则必须使用 {} 语句导入。
最好的理解方法是通过源代码。
【讨论】:
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。
【讨论】: