How to put an onClick event on an font awesome icon in react?

人走茶凉 提交于 2020-05-15 00:52:28

问题


I am trying to set an onClick event on a fontawesome icon but it doesnt work when I do this.

 <i class="fab fa-accessible-icon" onClick={this.removeItems}></i>

It only works when I put the onClick on p tags or h tags like this.

 <h1 onClick={this.removeItems}><i class="fab fa-accessible-icon"></i></h1>

It is not possible to set event on icon itself? Doing this the second way is causing me style errors.

Edit: I did change the class to className, my bad. but its still not working and currently im bypassing it using around the icon and having the onClick on the span.


回答1:


Here you can look into react docs which explains to use className instead of class. Also wrap your <i> tag in button tag and use onClick() function there.




回答2:


Perhaps try

<i className="fab fa-accessible-icon" onClick={this.removeItems}></i>

I was able to get

<i onClick={doSomething}>Testing</i>

to handle the click event, but it was rendered as jsx (ala render() method) -- assuming you are doing likewise.




回答3:


Well it should work like below...

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<i class="fa fa-cog" onClick="console.log('Clicked')"></i>

If its not try to wrap your icon into a button

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<button><i class="fa fa-cog" onClick="console.log('Clicked')"></i></button>



回答4:


You are confusing JSX with HTML. The i tag you have in your code is not plain html tag it is a javascript object(read more about jsx here). React takes care of binding the events for you, don't worry if you can't see onClick in your html.




回答5:


Change class attribute to ClassName <i className="fab fa-accessible-icon" onClick={this.removeItems}></i> I think its work. check the demo https://stackblitz.com/edit/react-nh2bqu




回答6:


If you're using react-fontawesome, you can use the FontAwesomeIcon component, and set both an id and an onClick:

<FontAwesomeIcon id={yourIdGoesHere} icon={faEdit}  onClick={this.editItem} />

...

editItem = event => {
  let idOfClickedIcon = event.currentTarget.id
  ...do something with the item associated with the id
}


来源:https://stackoverflow.com/questions/49443181/how-to-put-an-onclick-event-on-an-font-awesome-icon-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!