最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why do I need to pass an anonymous function into the onClick event? - Stack Overflow

programmeradmin4浏览0评论

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 as such:

        <button className="square" onClick={() => {alert("click");}}>
            {this.state.value}
        </button>

I don't understand why the arrow function is required - why can't I just have the alert() on its own?

The docs state:

Forgetting () => and writing onClick={alert('click')} is a common mistake, and would fire the alert every time the component re-renders.

Which is correct - I've tried this, and it does continually call alert(). But why? Isn't it supposed to fire onClick, and not on render? What does the anonymous function do that stops this behaviour?

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 as such:

        <button className="square" onClick={() => {alert("click");}}>
            {this.state.value}
        </button>

I don't understand why the arrow function is required - why can't I just have the alert() on its own?

The docs state:

Forgetting () => and writing onClick={alert('click')} is a common mistake, and would fire the alert every time the component re-renders.

Which is correct - I've tried this, and it does continually call alert(). But why? Isn't it supposed to fire onClick, and not on render? What does the anonymous function do that stops this behaviour?

Share Improve this question asked Aug 7, 2019 at 10:46 WomblersWomblers 1831 silver badge7 bronze badges 1
  • 3 Because you're passing a function to be called, instead of calling the function and passing the result. {alert("click")} is invoking the function, like {(() => alert("click"))()}. – jonrsharpe Commented Aug 7, 2019 at 10:48
Add a comment  | 

3 Answers 3

Reset to default 12

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

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>
}

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)

  1. 暂无评论