Why should event handlers be references, not calls?

The React tutorial says:

Execution onClick={alert('click')}will warn immediately, but not at the click of a button.

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

However, I cannot understand why this would be ... can someone clarify this for me, please? Why can't you pass a function call as a handler?

+4
source share
2 answers

When you execute onClick={alert("click")}, that will call the function alertand assign the return value ( undefined) to the property onClick. So, what React sees is what it onClick={undefined}says: well, that is not a function, why should I add such a handler?

, onClick, , undefined.

, : onClick={myFunction} myFunction () => alert("..."), , bind :

onClick={alert.bind(window, "click")}

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);

onClick thingy:

onClick={sayHelloTo("Alice")}

, ( , , , ):

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
+9

, , . , , , , . JSX, , , .

, , alert('click'), , . , alert ( undefined) - . , , .

:

function on(event, handler) {
    //some event listener function that runs the handler when event happens
    //then we call handler when the event happens:
    handler();
}

, on('click', alert('test')), alert('test'), , undefined. undefined(), . , , .

+4

Source: https://habr.com/ru/post/1678558/


All Articles