Arrow function without curly braces

前端 未结 7 1089
生来不讨喜
生来不讨喜 2020-11-22 10:52

I\'m new to both ES6 and React and I keep seeing arrow functions. Why is it that some arrow functions use curly braces after the fat arrow and some use parentheses? For exam

7条回答
  •  失恋的感觉
    2020-11-22 11:14

    The parenthesis are returning a single value, the curly braces are executing multiple lines of code.

    Your example looks confusing because it's using JSX which looks like multiple "lines" but really just gets compiled to a single "element."

    Here are some more examples that all do the same thing:

    const a = (who) => "hello " + who + "!";
    const b = (who) => (
        "hello " + 
        who + 
        "!"
    );
    const c = (who) => {
      return "hello " + who + "!";
    }; 
    

    You will also often see parenthesis around object literals because that's a way to avoid the parser treating it as a code block:

    const x = () => {} // Does nothing
    const y = () => ({}) // returns an object
    

提交回复
热议问题