简体   繁体   中英

<a onClick is calling without clicking

I should use

<a href="url">Something/>

So when I click on it, it redirects me to my URL.

But now I wanna do the same with the onClick method (to use my router).

In my code I try to use it:

<a onClick={this.changeRoute()}>Something/>

But this redirects me directly without clicking on it .... I expect that the results are that it calls my function after I click on it. What don't I understand?

Because you are calling it right away. Remove () from html.

Should be like this: <a onClick={this.changeRoute}>Something/>

With parenthesis, you execute the function. To solve your problem, remove it.

<a onClick={this.changeRoute}>Something</a>

By using parentheses you are executing the function and passing the result as the thing to be executed. You are basically saying execute this.changeRoute() and onClick do the result of this.changeRoute() . Instead you want to do this.changeRoute() onClick. You can either do

<a onClick={(e) => this.changeRoute()}>Something</a>

or

<a onClick={this.changeRoute}>Something</a>

This first example "ensures this is bound within" changeRoute. Otherwise you will have to call a bind function on the function in the second example.

The second example passed the actual function instead of the result of the function.

In other examples, you may want to return a function when this.changeRoute is called, in which case your syntax would work just fine, because you would indeed be using the return value as the function to be called.

For more information take a look at https://reactjs.org/docs/handling-events.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM