gpt4 book ai didi

javascript - 没有大括号的 ES6 箭头函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:26:36 25 4
gpt4 key购买 nike

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

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

上面是否等同于:

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

?

最佳答案

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

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

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

关于javascript - 没有大括号的 ES6 箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41526881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com