如果没有箭头函数(常规函数),我将如何重写它

ben*_*boy 0 javascript

我不太擅长箭头函数,希望进行一些从箭头函数更改为常规函数的练习。这是在 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)

Cod*_*ing 5

箭头参数

箭头函数有几种一般形式。

  • 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