Any difference between React.Component and Component?

前端 未结 3 1442
名媛妹妹
名媛妹妹 2021-01-21 22:18

I have seen two ways of accessing Component:

import React from \'react\';

class Foo extends React.Component {
    ...
}

and

相关标签:
3条回答
  • 2021-01-21 22:48

    No, it's just a matter of what you import into the local namespace. If you already have something called Component locally, you wouldn't be able to do the latter. Other than that it's just preference, whether you want to list everything that's imported up top, or instead be able to easily see which module something is from at usage sites.

    0 讨论(0)
  • 2021-01-21 22:53

    In first example you got the whole exports through import React, and you call Component through react import. In second example you import Component separately from React. That's why you don't need to write React.Component. It's the same, but in different ways of import.

    0 讨论(0)
  • 2021-01-21 23:04

    Short answer: no.

    Looking at it from the other side might make understanding easier.

    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;
    

    Notice the use of export.

    The default export is React, so it is accessed (or imported) in another module like this:

    import React from 'react';
    

    Component is a named export: Component, and so is accessed in another module via:

    import { Component } from '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 {}
    

    A few other points worth mentioning:

    • 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.
    0 讨论(0)
提交回复
热议问题