我不太擅长箭头函数,希望进行一些从箭头函数更改为常规函数的练习。这是在 React 中。
function render() {
const todoItems = this.state.todos.map(
item => <TodoItem
key={item.id}
item={item}
handleChange={this.handleChange}
/>
);
Run Code Online (Sandbox Code Playgroud)
箭头函数有几种一般形式。
arg1 => 严格针对一个参数(arg1, arg2) => 多个参数,用括号括起来。() => 没有参数也需要括号在箭头的另一边,还有另外2种形式:
=> value返回值(或表达式的结果)=> {someStatements;}不隐式返回任何内容。function()转换为函数时,请遵循下表:
arg1 => 变成function(arg1)(arg1, arg2) => 变成function(arg1, arg2)=> value变成function(args) { return value }=> { someStatements;}变成function(args) { someStatements;}this:箭头函数不同最后,一个微妙但重要的区别。箭头函数使用this其包装器。用关键字声明的函数function总是有自己的this.
因此,在这种特殊情况下,给定todos.map(item => <Component />),函数为 ,item => <Component />从上表向后推算,我们可以看到这相当于函数function(item) { return <Component />; }
完整的行看起来像这样:
const outerThis = this; //save with a different name so we can access within function
const todoItems = this.state.todos.map(
function(item) {
return <TodoItem key={item.id} item={item} handleChange={outerThis.handleChange}/>
}
)
Run Code Online (Sandbox Code Playgroud)
另请参阅MDN 上的箭头函数表达式,您可以在其中了解一些其他箭头函数注意事项(例如 no 、argumentsor )和运算符。newprototypeyieldthis