简体   繁体   中英

make href call a method in reactjs

I would like to make the href attribute of my anchor tag to call a method instead of going to some url. I know that in plain js I can do this:

..href={"javascript: foo(value)">

So I've done the same in my jsx file:

<a href={javascript: ()=>foo(value)}>Click Here!</a>

but it doesn't work. How it can be done?

use reacts onClick

You can use onClick on an element in react. like this

<a onClick={()=>foo(value)}>Click Here!</a>

That being said, if the purpose of your a tag is not to go to a link then your html is incorrect and you should think about using a button tag instead

而是使用按钮,并且onClick的开头不需要JavaScript。

<button onClick={() => doSomething("Hello") }>Click Me</button>

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