React Js获取被点击的元素

时间:2017-02-24 09:30:18

标签: javascript jquery reactjs

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")
        );    

每当我点击按钮sendMsg时,我想要sendMsg函数内的按钮元素。

但是每当我点击按钮e.target的span或child元素时,都会返回span / child元素而不是按钮本身(我知道这是e.target的作用)

但是我如何获得被点击的元素?

在Jquery中可以使用

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

我如何获得确切的元素?

3 个答案:

答案 0 :(得分:5)

您应该使用e.currentTarget代替e.target

示例:

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

希望这有帮助!

答案 1 :(得分:2)

使用react refs,这样就可以避免使用Jquery和DOM选择器了。

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>
    );

  }
});

答案 2 :(得分:0)

与您的问题无关,但我这样做是为了避免使用jQuery&amp;从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")
);