es6箭头功能中的每个花括号 [英] curly braces in es6 arrow function for each

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

问题描述

我们创建像这样的表示性组件或无状态组件

We create presentational component or stateless component like this

const MyComponent = () => {
   return(<div>my component</div>)
}

但我见过

const MyComponent = () =>
   <div>
     <h1>head</h1>
     my component
   </div>

所以现在我在使用es6的箭头功能时需要大括号时感到困惑.

so now I'm confused when the braces is needed when using es6's arrow function.

当使用地图渲染列表时,这让我感到困惑

This confused me on when rendering a list using map

短版

<div>
{map(o => 
   <div>{o.name}</div>
)}
</div>

较长版本

<div>
    {map(o => {
     return(<div>{o.name}</div>)
     })}
</div>

两个都是正确的,但是为什么要写更长的时间呢?

Both are correct, but why write longer?

推荐答案

{map(o => // without curly brackets 
   <div>{o.name}</div> // this will be returned implicitly
)}

{map(o => { // with curly brackets
    return <div>{o.name}</div> // you need to return explicitly
    } 
)}

如果使用大括号, 您必须明确地返回数据,

If you do curly brackets , You have to explicilty return the data ,

何时使用哪个?

When to use which one?

当您执行多行代码时,您需要使用大括号并从中返回

When you have mutliple line of execution you need to do curly brackets and return from it

但是如果您只执行一行,则需要返回,则不需要大括号和return,它会隐式返回.

But if you have single line of execution, that you need to return , then there is no need of curly brackets and return , it will return implicitly.

与条件相同

Same as If condition

if(true)
    // do this for single line
else
    // do this for single line




if() {
    // do this for multiple line
} else {
    // do this for multiple line
}   

这篇关于es6箭头功能中的每个花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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