What is the purpose of 'export' in React component declaration?

前端 未结 2 752
鱼传尺愫
鱼传尺愫 2021-02-05 12:54

In React (ES6), why do I sometimes see this?...

class Hello extends React.Component { ... }

and sometimes this?



        
2条回答
  •  滥情空心
    2021-02-05 13:55

    Exporting a value allows you to import it into another file.

    If I export this class from the hello.js file:

    // hello.js
    export class Hello extends React.Component { ... }
    

    Then I can import it and use it in the greeting.js file.

    // greeting.js
    import { Hello } from './hello';
    
    export class Greeting extends React.Component {
      render() {
        return ;
      }
    }
    

    This isn't specific to React and you can use this syntax to import and export any kinds of values in any kinds of JavaScript applications.

    After you use a tool like Babel to turn this into code that can run in a browser, then you can use a tool like Webpack to bundle all the modules you have used into a single script file that you can serve for the browser.

    This module syntax for importing and exporting also provides a useful shorthand for modules that export a "default" value.

    // hello.js
    export default class Hello extends React.Component { ... }
    
    // greeting.js
    import Hello from './hello';
    

    Generally you'd want to use this form if your module only exports one value.

提交回复
热议问题