为什么事件处理程序需要引用而不是调用?

cof*_*eak 5 javascript reactjs

React教程中,它说

执行onClick={alert('click')}会立即发出警报,而不是单击按钮时.

class Square extends React.Component {
  render() {
    return (
      <button className="square" onClick={() => alert('click')}>
        {this.props.value}
      </button>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,我无法理解为什么会这样......有人可以为我澄清这个吗?为什么不能将函数调用作为处理程序传递?

Ion*_*zău 11

当你这样做时onClick={alert("click")},将调用该alert函数并将返回的值(undefined)分配给onClick属性.那么,React看到的是,onClick={undefined}并说:嗯,这不是一个函数,为什么我会添加这样的处理程序?

你要传递的onClick是一个函数,而不是undefined.

因此,你必须做的:onClick={myFunction}哪里myFunction可以() => alert("...")为你所提到的,也可以使用bind创建类似的功能:

onClick={alert.bind(window, "click")}
Run Code Online (Sandbox Code Playgroud)

bind返回一个新函数,该alert函数将在内部使用"click"参数调用该函数.


类似的情况就是当你这样做的时候setTimeout(() => alert("after 1 second"), 1000).setTimeout期待一个功能.如果你这样做setTimeout(alert("..."), 1000),那么alert确实会调用,但是setTimeout会作为第一个参数接收undefined(这就是alert返回的内容).

相反,如果你有一个函数返回一个函数,那将是有效的:

// This will be called first and will return a function
const sayHelloTo = name => {
   // This will be the function passed to `setTimeout`
   return () => alert(`Hello ${name}`);
};
setTimeout(sayHelloTo("Alice"), 1000);
Run Code Online (Sandbox Code Playgroud)

您可以以相同的方式使用它onClick:

onClick={sayHelloTo("Alice")}
Run Code Online (Sandbox Code Playgroud)

这是关于背景中发生的事情的一个非常小的例子(它只是一个概念证明,我确定它实际发生的事情比这更好):

const elm = {
  onClick: null,
  // The click method can be invoked manually
  // using `elm.click()` or is natively invoked by the browser
  click () {
     if (typeof this.onClick === "function") {
        this.onClick();
     }
  }
};

// If you do:
elm.onClick = alert("click"); // this calls the alert, and returns undefined
elm.onClick === undefined // true

// But when doing:
elm.onClick = () => alert("click");
typeof elm.onClick // "function"

elm.click(); // this will call the alert
Run Code Online (Sandbox Code Playgroud)