Calling a javascript function in JSX: why does calling a function without the () work?

前端 未结 2 913
广开言路
广开言路 2021-01-01 05:50

Currently on Codecademy and learning about React.

Came to this code:

2条回答
  •  感动是毒
    2021-01-01 06:34

    Without parenthesis, you're not calling the function. The name of the function without the parenthesis is a reference to the function. Parentheses is not used in the function at that point because we are not calling the function at the point where the code is encountered, but instead want to pass a reference to the function. If you use makeDoggy() , the function will get called at that point, we instead want it to be called only after onClick, so we pass a reference to makeDoggy there.

    Alternatively you can do onClick={()=>makeDoggy()}

    e gets bound automatically using something called property initializer in es6.

提交回复
热议问题