dki*_*mot 47 javascript ecmascript-6 react-jsx arrow-functions
我是ES6和React的新手,我一直在看箭头功能.为什么有些箭头函数在胖箭头之后使用花括号而有些使用括号?例如:
const foo = (params) => (
<span>
<p>Content</p>
</span>
);
Run Code Online (Sandbox Code Playgroud)
与
const handleBar = (e) => {
e.preventDefault();
dispatch('logout');
};
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
dav*_*vid 92
括号返回单个值,花括号执行多行代码.
您的示例看起来令人困惑,因为它使用的JSX看起来像多个"行",但实际上只是编译为单个"元素".
以下是一些例子,它们都做同样的事情:
const a = (who) => "hello " + who + "!";
const b = (who) => (
"hello " +
who +
"!"
);
const c = (who) => {
return "hello " + who + "!";
};
Run Code Online (Sandbox Code Playgroud)
您还经常会看到围绕对象文字的括号,因为这是一种避免解析器将其视为代码块的方法:
const x = () => {} // Does nothing
const y = () => ({}) // returns an object
Run Code Online (Sandbox Code Playgroud)
Gra*_*Fox 16
也可以使用花括号来防止单行箭头函数返回一个值 - 或者让下一个开发人员明白单行箭头函数不应该返回任何东西.
例如:
const myFunc = (stuff) => { someArray.push(stuff) }
const otherFunc = (stuff) => someArray.push(stuff)
console.log(myFunc()) // --> logs undefined
console.log(otherFunc()) // --> logs result of push which is new array length
Run Code Online (Sandbox Code Playgroud)
括号在箭头函数中用于返回一个对象。
() => ({ name: 'YourName' }) // This will return an object
Run Code Online (Sandbox Code Playgroud)
那相当于
() => {
return { name : 'YourName' }
}
Run Code Online (Sandbox Code Playgroud)
实际上,在公文包中,当有人在箭头函数声明中使用大括号时,它等于以下内容:
const arrow = number => number + 1;
|||
const arrow = (number) => number + 1;
|||
const arrow = (number) => ( number + 1 );
|||
const arrow = (number) => { return number + 1 };
Run Code Online (Sandbox Code Playgroud)
小智 6
如果在箭头后面使用大括号来定义函数体,则必须使用“return”关键字来返回某些内容。
例如:
const myFun1 = (x) => {
return x;
}; // It will return x
const myFun2 = (x) => {
x;
}; // It will return nothing
Run Code Online (Sandbox Code Playgroud)
如果使用括号,则无需提及“return”关键字。
例如:
const myFunc1 = (x) => x; // It will return x
const myFunc2 = (x) => (x); // It will also return x
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10561 次 |
| 最近记录: |