没有花括号的箭头函数 [英] Arrow function without curly braces
问题描述
我是 ES6 和 React 的新手,我一直看到箭头函数.为什么有些箭头函数在粗箭头后使用花括号,有些使用括号?例如:
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 example:
const foo = (params) => (
<span>
<p>Content</p>
</span>
);
对比
const handleBar = (e) => {
e.preventDefault();
dispatch('logout');
};
推荐答案
括号返回单个值,大括号执行多行代码.
The parenthesis are returning a single value, the curly braces are executing multiple lines of code.
您的示例看起来令人困惑,因为它使用的是 JSX,看起来像多行";但实际上只是被编译为单个元素".
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) => (
"hello " + who + "!"
);
const d = (who) => (
"hello "
+ who
+ "!"
);
const e = (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
这篇关于没有花括号的箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!