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

后端 未结 3 1007
刺人心
刺人心 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: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);

提交回复
热议问题