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

前端 未结 2 751
鱼传尺愫
鱼传尺愫 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:36

    Before explain the export keyword let me clear something to you.


    As you have seen around the internet, in every react application you need to use two important things:

    1/ Babel

    2/ webpack or browserify

    Explaination

    What is Babel job?

    You might heard of jsx and ES6.

    Well, Babel job is Transpile the jsx to js and ES6 to ES5 so the browser can understand these two things.

    And export keyword is a new feature in ES6 let export your functions, variables so you can get access to them in other js files.

    ie:

    hello.js

    export default class Hello extends React.Component {
      render() {
        return 
    Hello
    } }

    world.js

    import { Hello } from './hello';
    
    class World extends React.Component {
      render() {
        return 
    world
    ; // jsx sytanx. } }

    What is webpack job?

    Webpack is a module bundler. It takes in a bunch of assets (ie. hello.js, world.js and your modules (react, react-dom....)) and turns that into one single file.

    i.e:

    let say that we have the following config for webpack

    // dont need to set hello.js as an entry because we already import it into world.js
    module.exports = {
    
      entry: [
        './src/world.js'  
      ],
      output: {
        path: __dirname,
        publicPath: '/',
        filename: 'bundle.js'
      }
    };
    

    webpack it turn all of your js files and your modules wich imported and it turn it into onne single file bundle.js.

    Edit: Solving the problem

    In jsx,

    always wrap the returned html into ().

    ...
    render() {
      return (
        

    Hello World (Main File this time)

    ) } ...

提交回复
热议问题