Why do I need to pass an anonymous function into the onClick event?

后端 未结 3 1006
刺人心
刺人心 2020-12-19 09:21

I\'ve been trying to learn the basics of React. However, I\'ve come across a section in the tutorial that asks me to place an alert() inside of an onClick event

相关标签:
3条回答
  • 2020-12-19 09:52

    Basically there is differences between calling (Invoking) a function alert() and Defining (Expressing) a function () => {alert()}

    When the code runs, i.e when react renders the component, any function call would run that function and that's why we can use IIFE (function() { } )() to inject functions to window object at runtime.

    However, handling events with inline function call (like onclick={()=>{alert()}}) is not recommended because every time that event triggered, a new instance of that function would be created and it may slow down your app,

    Instead you can DEFINE a function for handling events and just call it when that specific event triggered:

    // Bad
    render() {
      return <button onclick={() => {this.setState({btnClicked: true})}}> Click! </button>
    }
    
    // Good
    render() {
    
      const handleClick = () => {
        this.setState({btnClicked: true})
      }
    
      return <button onclick={handleClick}> Click! </button>
    }
    
    0 讨论(0)
  • 2020-12-19 09:53

    Because if you call a function, then the function runs. (And you get the return value from it)

    const onClick = alert("hello");
    console.log(onClick);

    If you define a function (X) that calls a function (Y), then it doesn't call Y until you call X.

    const onClick = () => alert("hello");
    console.log(onClick);

    0 讨论(0)
  • 2020-12-19 09:58

    Because you need a function that gets called only in the instant that the button is clicked. If you pass alert('click') then the parser will find a function call and execute it instantly when it is going over that file.

    0 讨论(0)
提交回复
热议问题