问题描述
我已经看到两种访问Component
的方法:
I have seen two ways of accessing Component
:
import React from 'react';
class Foo extends React.Component {
...
}
和
import React, { Component } from 'react';
class Foo extends Component {
...
}
两者之间是否有区别(例如,在性能上)?
Is there any difference between the two (maybe in performance, for example)?
推荐答案
简短答案:否.
从另一端看它可能会使理解变得更容易.
Looking at it from the other side might make understanding easier.
如果您想像一下react模块本身-它可能看起来像这样.
If you imagine the react module itself - it might look something like this.
export const Component = () => {}; // the component class/function
const React = { Component: Component }; // the main react object
export default React;
注意使用export
.
默认 export
是React,因此可以在另一个模块中访问(或导入)它,如下所示:
The default export
is React, so it is accessed (or imported) in another module like this:
import React from 'react';
Component是一个已命名的导出文件:Component
,因此可以通过以下方式在另一个模块中进行访问:
Component is a named export: Component
, and so is accessed in another module via:
import { Component } from 'react';
但是在这种情况下,组件也被附加到React对象.因此,您可以通过以下任何一种方式使用导入:
But in this case Component is also attached to the React object. So you could use the imports in any of the following ways:
import React, { Component } from 'react';
class MyComp extends React.Component {}
class MyOtherComp extends Component {}
其他几点值得一提:
- 每个模块只能导出一个默认,但是您可以导出许多变量.
- 默认导出在导入时可以命名为任何名称.例如
import Cat from 'react';
. - 您可以通过执行以下操作来重命名已命名的导入:
import { Component as Cat } from 'react';
- 此行为并非特定于React,而是ES6模块系统的一部分.
- There can only be one default export per module, but you can export many variables.
- The default export can be named anything when you import it. For example
import Cat from 'react';
. - You can rename named imports by doing the following:
import { Component as Cat } from 'react';
- This behavior isn't specific to React, but is part of the ES6 module system.
这篇关于React.Component和Component之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!