What does “export default” do in JSX?

后端 未结 5 1738
心在旅途
心在旅途 2020-12-07 07:42

I want to ask what the last sentence means and does (export default HelloWorld;) but I can\'t find any tutorials about it.

// hello-world.jsx

import React f         


        
5条回答
  •  误落风尘
    2020-12-07 08:32

    export default is used to export a single class, function or primitive from a script file.

    The export can also be written as

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

    Hello, world!

    ; } }

    You could also write this as a function component like

    export default const HelloWorld = () => (

    Hello, world!

    );

    This is used to import this function in another script file

    import HelloWorld from './HelloWorld';
    

    You don't necessarily import it as HelloWorld you can give it any name as it's a default export

    A little about export

    As the name says, it's used to export functions, objects, classes or expressions from script files or modules

    Utiliites.js

    export function cube(x) {
      return x * x * x;
    }
    export const foo = Math.PI + Math.SQRT2;
    

    This can be imported and used as

    App.js

    import { cube, foo } from 'Utilities';
    console.log(cube(3)); // 27
    console.log(foo);    // 4.555806215962888
    

    Or

    import * as utilities from 'Utilities';
    console.log(utilities.cube(3)); // 27
    console.log(utilities.foo);    // 4.555806215962888
    

    When export default is used, this is much simpler. Script files just exports one thing. cube.js

    export default function cube(x) {
      return x * x * x;
    };
    

    and used as App.js

    import Cube from 'cube';
    console.log(Cube(3)); // 27
    

提交回复
热议问题