箭头功能无花括号 [英] Arrow function without curly braces

查看:107
本文介绍了箭头功能无花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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>
);

vs。

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) => {
  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆