最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing current element to onClick function - React Jsx - Stack Overflow

programmeradmin4浏览0评论

I have a div, i want to pass this div to onlick function and change it's class (or add class).

<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.

What i want is:

handleHistoryClick(el){
     $(el).addClass('active');
}

EDIT: I have multiple history-node elements. So adding state to change class won't work for multiple elements.

How do i achieve this?

I have a div, i want to pass this div to onlick function and change it's class (or add class).

<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.

What i want is:

handleHistoryClick(el){
     $(el).addClass('active');
}

EDIT: I have multiple history-node elements. So adding state to change class won't work for multiple elements.

How do i achieve this?

Share Improve this question edited Oct 18, 2017 at 14:03 Noman Ali asked Oct 18, 2017 at 13:55 Noman AliNoman Ali 3,34013 gold badges47 silver badges79 bronze badges 3
  • Possible duplicate of react change class name on state change – azium Commented Oct 18, 2017 at 13:59
  • No it's not. Because i have multiple history-node elements. How to determine states for all of them? only one can have active state. – Noman Ali Commented Oct 18, 2017 at 14:01
  • store an array of states then, not just one – azium Commented Oct 18, 2017 at 14:20
Add a ment  | 

2 Answers 2

Reset to default 9

this in your code refer to the ponent and not the element:

<div className="history-node" onClick={() => this.handleHistoryClick}>
     <span className="history-title">Uploaded</span>
     <span className="history-date">October 9, 2017</span>
</div>

ponent :

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. just like this :

constructor(){
   this.handleHistoryClick= this.handleHistoryClick.bind(this);
}

Instead of using this.handleHistoryClick(this)}>

use this...

this.handleHistoryClick.bind(this)}>

发布评论

评论列表(0)

  1. 暂无评论