gpt4 book ai didi

javascript - 箭头函数语法用括号而不是花括号?

转载 作者:行者123 更新时间:2023-12-02 21:32:06 25 4
gpt4 key购买 nike

我在 React 教程中看到了一段代码片段:

const App = ({title}) => (
<div className="header">{title}</div>
);

乍一看,我以为它给 App 分配了一个箭头功能持续的。然后我注意到它不使用花括号而是括号。

我理解箭头函数应该是 (...) => {...} ,但这里使用 (...) => (...)

那么,它到底是不是箭头函数呢?如果是的话,为什么还有另一种形式?我如何决定何时使用哪种表格?如果不是的话,这个函数类型在js中调用的是什么?

最佳答案

是的,它也是一个箭头函数。唯一的区别是,如果不使用大括号,它会强制返回:

const App = () => { return true; } // with braces you've to use the return statement

const App = () => true; // without braces it forces the return statement automatically

MDN arrow function expression documentation对此有如下说法:

Function body

Arrow functions can have either a "concise body" or the usual "blockbody".

In a concise body, only an expression is specified, which becomes theimplicit return value. In a block body, you must use an explicitreturn statement.

var func = x => x * x;
// concise body syntax, implied "return"

var func = (x, y) => { return x + y; };
// with block body, explicit "return" needed

此外,关于括号:本例中的箭头函数返回一个 JSX 表达式,它被视为单个对象。括号主要用于多行 JSX 代码。在这里查看更多信息:https://reactjs.org/docs/introducing-jsx.html还有关于堆栈溢出的其他类似问题。

关于javascript - 箭头函数语法用括号而不是花括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60596873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com