【问题标题】:ES6 Arrow function without curly braces没有花括号的 ES6 箭头函数
【发布时间】:2017-05-22 11:11:41
【问题描述】:

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

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

以上是否等同于:

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

?

【问题讨论】:

  • 那不是 ES6。可能是 JSX。
  • 是的,但是您需要用反引号包裹 HTML。而字符串参数需要一个前导$...${param}
  • @Mottie 是的,是一样的吗?
  • @Mottie 这是 JSX,不是 HTML,所以,不,他没有。
  • 如果你有一个返回值,不需要添加返回。

标签: javascript reactjs ecmascript-6 jsx


【解决方案1】:

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

由于&lt;div&gt;&lt;label&gt;{props.placeholder}&lt;/label&gt;&lt;/div&gt; 实际上是一个表达式(它被转换为React.createElement(......) 或类似的东西),并且您希望从renderInput 返回它,这确实是您使用无括号的方式箭头函数的版本。

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

【讨论】:

  • 所以确实是const renderInput = function renderInput(props),重复renderInput 两次?
  • 无论如何,您只能在递归中使用该函数名。如果函数没有名称,浏览器的 devtools 将分配名称 const,因此两者几乎是等价的。严格来说,相当于const renderInput = function(props) {而不是function renderInput(props)。
  • @softcode:您可能想阅读Named function expressions demystified
猜你喜欢
  • 2022-01-19
  • 2018-04-25
  • 2016-05-28
  • 2019-02-25
  • 2016-12-08
  • 2020-06-21
  • 1970-01-01
  • 2017-07-21
相关资源
最近更新 更多