每个 的 es6 箭头函数中的花括号

IT技术 javascript reactjs ecmascript-6 jsx
2021-05-16 08:57:40

我们像这样创建展示组件或无状态组件

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

但我见过这个

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

所以现在我很困惑在使用 es6 的箭头函数时需要大括号。

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

较短的版本

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

更长的版本

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

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

3个回答
{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
    } 
)}

如果你做大括号,你必须明确返回数据,

什么时候用哪一种?

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

但是如果你有单行执行,你需要 return ,那么就不需要大括号和 return ,它会隐式返回。

与 If 条件相同

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
}   

箭头函数可以双向工作,为您提供一些多功能性。假设您需要在返回之前在函数内部执行一些逻辑,在这种情况下您需要添加花括号,即假设您需要提取用户列表的名称,但您想附加他们的标题。

let users = [new User(), ... ];
//...

let withTitle = users.map(p => {
   const title = getTitle(p); // automagically returns Mr, Mrs, etc
   return `${title} ${p.fullName}`
});

// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']

现在,您可以声明一个为您完成工作的函数,并使用箭头函数的简写版本。像这样。

const extractWithTitle: (user) => {
   const title = getTitle(p); // automagically returns Mr, Mrs, etc
   return `${title} ${p.fullName}`
}

let withTitle = users.map(p => extractWithTitle(p));
// withTitle => ['Mr Ricky Bobby', 'Mr Ron Burgundy']

现在,解决这个问题的一种更短的方法是传递对函数的引用。

users.map(extractWithTitle);

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

如果你需要在箭头函数中添加更多的句子而不是jsx组件,你基本上需要使用更长的版本

例如

<div>
    {map(o => {
       const name = "My name is: " + o.name;
       return(<div>{name}</div>)
     })}
</div>

否则,您可以使用简短版本。