导入React,{Component}而不是React的好处是什么? [英] What is the benefit importing React, {Component} instead of just React?

查看:49
本文介绍了导入React,{Component}而不是React的好处是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

写作的主要好处是什么

import React, { Component } from 'react';
class Link extends Component {
   ...
}

代替

import React from 'react';
class Link extends React.Component {
   ...
}

当做出反应15.4.x时?

when it comes to react 15.4.x??

我的观点就我的情况(如果我错了,请纠正我),这根本没有关系,因为:

In my perspective and in my case (correct me if I am wrong) it does not matter at all since:

  1. 我正在使用 webpack2 制作捆绑包;
  2. 我使用代码拆分功能将我的应用程序代码与供应商代码拆分;
  3. 我将 webpack.optimize.CommonsChunkPlugin 插件与 minChunks:Infinity 设置结合使用,以确保所有供应商代码仅包含一次.
  1. I am using a webpack2 for making my bundles;
  2. I use code splitting to split my app code from vendor code;
  3. I use webpack.optimize.CommonsChunkPlugin plugin with minChunks: Infinity setting to make sure that all vendor code is included only once.

通过了解ES6导入的工作原理,我了解到通过使用 {Component} 的命名导入,我声明我只想在我的代码中使用 Component 组件,看起来.. 清洁工.但是,由于整个 React 包仍在应用程序中使用,因此我可以使用 React.Component 扩展名创建类,而不仅仅是 Component 和结果webpack仍将产生相同数量的代码,并且两种情况下我的包大小均相同.

From understanding how ES6 imports work I understand that by using named import of {Component} I state that I want to use only Component component in my code, which looks.. cleaner. But since whole React package is still used in the app, I can create my classes with extension from React.Component instead of just Component and in result webpack will still produce the same amount of code and my bundle size will be the same in both cases.

我正确吗?

推荐答案

没有区别, React.Component Component 是同一对象,第二种方法是我认为这更为雄辩,因为它确实说明您正在使用 React 库中的 Component 对象.

There is no difference, React.Component is the same object as Component, the second way is more eloquent in my opinion, because it really explains that you are using the Component object from the React library.

第一个似乎是指一个成员,但是,它来自javascript的 pre模块时代,在此时代,所有内容都必须附加到导出的全局名称空间中(只是为了避免全局名称空间污染).

The first one seems to refer a member, but, it comes from the pre modules era of javascript, where everything had to be attached to the exported global namespace (just to avoid global namespace pollution).

可能在幕后的东西:

// this should be assumed as an example only.

class React { ... }
class Component { ... }


React.Component = Component;

// ES6
export {Component}
export default React;

// ES5
window.React = React;

注意:正如某人所说,您还需要导入 React ,因为 JSX 需要将其置于范围内,但是,如果要避免它,则可以公开全局 React ( window.React = React )

Note: as someone said, you also need to import React because JSX needs to have it on scope, but, if you want to avoid it, you can expose React globally (window.React = React)

这篇关于导入React,{Component}而不是React的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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