没有大括号的 ES6 箭头函数

ES6 Arrow function without curly braces

我很难理解以下 ES6 语法。我阅读了很多文档,似乎这里发生了不止一个变化:

const renderInput = props =>
  <div>
    <label>{props.placeholder}</label>
  </div>

以上是否等同于:

const renderInput = function renderInput(props) {
  return <div>
           <label>{props.placeholder}</label>
         </div>
}

?

是的,没错。当你只有一个 表达式,并且它是你希望从函数中 return 的表达式时,你可以省略大括号。

因为 <div><label>{props.placeholder}</label></div> 实际上是一个表达式(它被转换为 React.createElement(......) 或类似的东西),并且您希望从 renderInput return ], 这确实是你使用箭头函数的无括号版本的方式。

如果您希望使用变量或进行一些其他计算(条件、for 循环等),则不能省略括号。