[英]Passing current element to onClick function - React Jsx
I have a div, i want to pass this
div to onlick function and change it's class (or add class). 我有一个div,我想
this
div传递给onlick函数并更改其类(或添加类)。
<div className="history-node" onClick={() => this.handleHistoryClick(this)}>
<span className="history-title">Uploaded</span>
<span className="history-date">October 9, 2017</span>
</div>
Function is: 功能是:
handleHistoryClick(el){
console.log("History Clicked");
console.log(el);
}
But this is printing current React Component Class which is Paymentdetail
. 但这是打印当前的React Component Class,它是
Paymentdetail
。
What i want is: 我想要的是:
handleHistoryClick(el){
$(el).addClass('active');
}
EDIT: I have multiple history-node
elements. 编辑:我有多个
history-node
元素。 So adding state to change class won't work for multiple elements. 因此,将状态添加到更改类将不适用于多个元素。
How do i achieve this? 我该如何实现?
this
in your code refer to the component and not the element: this
在您的代码中是指组件而不是元素:
<div className="history-node" onClick={() => this.handleHistoryClick}>
<span className="history-title">Uploaded</span>
<span className="history-date">October 9, 2017</span>
</div>
component : 零件 :
handleHistoryClick(event){
let el = event.target;
el.classList.add('active');
// $(el).addClass('active'); I'm not familiar with jquery but try it
}
edit : As @sag1v said : it is better to bind the handler in the constructor (or use arrow function) instead of creating a new function instance on each render. 编辑 :正如@ sag1v所说:最好在构造函数中绑定处理程序(或使用箭头函数),而不是在每个渲染器上创建新的函数实例。 just like this :
像这样 :
constructor(){
this.handleHistoryClick= this.handleHistoryClick.bind(this);
}
Instead of using this.handleHistoryClick(this)}> 而不是使用this.handleHistoryClick(this)}>
use this... 用这个...
this.handleHistoryClick.bind(this)}> this.handleHistoryClick.bind(this)}>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.