箭头函数的差异和ReactJS中没有箭头函数?

时间:2018-03-13 13:01:28

标签: javascript reactjs arrow-functions

我目前很困惑我们应该何时使用箭头功能以及何时不应该使用箭头功能。我对此进行了搜索,但我还不清楚。例如,我创建了一个按钮来计算点击次数,代码如下:

 class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {counter: 0};
  }
  buttonPressedIncrease = () => {
    this.setState((prevState) => {
      return {counter: prevState.counter + 1}
    });
  }
  render() { 
    return (
      <div>
        <div>Counter: {this.state.counter}</div>
        <button onClick={this.buttonPressedIncrease}>+</button>
      </div>
    );
  }
}

当我在按钮上使用箭头功能时,这样: onClick = {()=&gt; this.buttonPressedIncrease} ,该函数不像我在上面的代码中使用的那样工作。

任何人都可以向我解释这个问题吗?箭头功能何时起作用?什么时候不起作用?

非常感谢提前。

3 个答案:

答案 0 :(得分:2)

您已将buttonPressedIncrease定义为“胖箭”功能:

buttonPressedIncrease = () => {

这意味着如果你写() => this.buttonPressedIncrease,你将传递一个返回该函数的匿名函数。 onClick想要一个做某事的函数,而不是一个返回另一个函数的函数。

由于在定义函数时使用了粗箭头,this已经正确绑定,因此您应该只传递函数的名称:

onClick={this.buttonPressedIncrease}

有时在JSX中,您会看到onClick={() => someFunction()}(请注意someFunction()正在调用,与您的示例不同),这可能是您混淆的根源。这是保持正确this范围的另一种方法,但每次调用render方法时都会以创建新函数为代价。因此,上述方法是优选的。

答案 1 :(得分:1)

简而言之,onClick等事件监听器希望为您要调用的函数提供引用

考虑到这一点:

onClick={this.buttonPressedIncrease}

是正确的,因为this.buttonPressedIncrease是对函数的引用,它是您要运行的函数。

然而,

onClick={() => this.buttonPressedIncrease}

不正确,因为虽然() => this.buttonPressedIncrease是函数引用,但它不是您要执行的函数。您不想执行匿名函数() => this.buttonPressedIncrease,而是要执行this.buttonPressedIncrease。请记住,仅使用()调用函数。忽略括号只返回它们的引用。这就是为什么它不起作用 - 匿名函数没有调用想要的函数。

但是,如果你愿意,你可以这样做:

onClick={() => this.buttonPressedIncrease()}

因为匿名函数会调用想要的函数。虽然我坚持以前的解决方案。

答案 2 :(得分:0)

请注意,箭头功能只是传统javascript函数(伪代码)的不同语法:

function funcName(arg1,arg2) {
  return returned_exp/value
}

箭头表示

const funcName = (arg1,arg2) => returned_exp/value

现在,请注意返回的表达式可以是此处的函数。

所以在你的代码中

<button onClick={this.onClickHandler}></button>

你只需传递一个需要在onClick上执行的函数。如下面的代码

<button onClick={() => this.onClickHandler()}></button>

传递一个函数,当执行该函数时执行函数this.onClickHandler(一组打开和关闭的括号调用函数)。 所以我们通常在需要将一些数据/对象/函数作为参数传递给onClickHandler时使用后一种方法,如下所示:

<button onClick={() => this.onClickHandler(this.props.requiredStuff)}></button>

希望这有帮助!