简体   繁体   中英

React Js get the element which was clicked

https://jsbin.com/diyenakife/edit?html,js,output

JSX

let MY = React.createClass({

 sendMsg : function(e){
     alert($(e.target).attr('data-id'));
     //sendMsgButton = ??

 },
  render: function() {
    return (


      <button is class = "send_msg"
      data-id = "10"
      onClick = {
        this.sendMsg
      } >
      Send Message
      <span> INSIDE SPAN </span> <span className = "sendMsgIcon" > ICON </span> </button>
    );

  }
});


        ReactDOM.render(
          <MY />,
          document.getElementById("container")
        );    

Whenever im clicking the button sendMsg i want the button element inside sendMsg function.

But whenever im clicking a span or child element of the button e.target returns the span/child element instead of button itself ( i know that's what e.target does)

But how do i get the element which was clicked ?

In Jquery its possible using

$('.sendMsg').click(function(){
  let sendMsgButton = $(this);
});

How do i get the exact element ?

You should use e.currentTarget instead of e.target

Example:

sendMsg : function(e){
  alert($(e.currentTarget).attr('data-id'));
  //sendMsgButton = ??
}

Hope this helps!

Use react refs so you can avoid using Jquery and DOM selectors.

https://jsbin.com/senevitaji/1/edit?html,js,output

let MY = React.createClass({

 sendMsg : function(e){
     alert(this.button.getAttribute('data-id'));
     //sendMsgButton = ??

 },
  render: function() {
    return (


      <button is class = "send_msg"
      data-id = "10"
      ref={(button) => { this.button = button; }} 
      onClick = {
        this.sendMsg
      } >
      Send Message
      <span> INSIDE SPAN </span> <span className = "sendMsgIcon" > ICON </span> </button>
    );

  }
});

Unrelated to your question, but this is how I would do this to avoid using jQuery & reading data form DOM.

https://jsbin.com/zubefepipe/1/edit?html,js,output

let Button = React.createClass({
  _onClick: function(e){
    e.preventDefault();
    this.props.onClick(e, this)
  },
  getSomeAttr: function(){
    return this.props.someAttr;
  },
  render : function() {
    return (
      <button onClick={this._onClick}>
        Send Message
        <span> INSIDE SPAN </span>
        <span className = "sendMsgIcon"> ICON </span>
      </button>
    );
  }
});

let MY = React.createClass({
 sendMsg : function(e, btn){
     alert(btn.getSomeAttr());
 },
  render: function() {
    return (
      <Button someAttr="10" onClick={this.sendMsg}/>
    );
  }
});


ReactDOM.render(
  <MY />,
  document.getElementById("container")
);   

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