简体   繁体   中英

Why does this event handler have access to the class properties when it is not in scope?

This snippet came from a medium article. Why does the first <button onClick={this.handleClick1()}>click 1</button> have access to the actual properties in the class?

/**
 * Can you explain the differences between all those ways
 * of passing function to a component?
 *
 * What happens when you click each of the buttons?
 */
/**
 * Can you explain the differences between all those ways
 * of passing function to a component?
 *
 * What happens when you click each of the buttons?
 */
class App extends React.Component {

  constructor() {
    super(); 
    this.name = 'MyComponent';

    this.handleClick2 = this.handleClick1.bind(this);
  }

  handleClick1() {
    alert(this.name);
  }

  handleClick3 = () => alert(this.name);
render() {
    return (
      <div>
        <button onClick={this.handleClick1()}>click 1</button>
        <button onClick={this.handleClick1}>click 2</button>
        <button onClick={this.handleClick2}>click 3</button>
        <button onClick={this.handleClick3}>click 4</button>
      </div>
    );
  }
}

Why does the first <button onClick={this.handleClick1()}>click 1</button> have access to the actual properties in the class?

this.handleClick1() invokes the function right then and there, ie not when the event is triggered later. handleClick1 returns undefined so no event handler is actually bound.

And since the function is called as object property ( xy() ), onClick1 's own this value is set to the value before the . (also this ).

因为与this绑定

this.handleClick2 = this.handleClick1.bind(this);

Function.prototype.bind

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM