如何从事件对象访问数据属性

时间:2016-06-20 18:55:13

标签: reactjs

jsfiddle

var Hello = React.createClass({
  handleClick(event){
    console.log('target info', event.currentTarget);
    console.log('event info', event);
    var sortOrder = event.currentTarget.sortorder;

    console.log('sortOrder: ', sortOrder);
    alert(sortOrder);//Should say "asc"
  },
  render: function() {
    return <div style={{backgroundColor: "red", fontSize: '5em'}} data-sortorder="asc" onClick={this.handleClick}>Click Here Please</div>;
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

预期输出: asc
实际:未定义

1 个答案:

答案 0 :(得分:13)

我更新了你的小提琴:

我只能通过引用“getAttribute”

来做到这一点
 event.target.getAttribute("data-sortorder");

这是refs https://jsfiddle.net/69z2wepo/46265/

 var sortOrder = this.refs.tester.getAttribute("data-sortorder");
 alert(sortOrder);//Should say "asc"
},
  render: function() {
    return <div style={{backgroundColor: "red", fontSize: '5em'}} data-sortorder="asc" ref="tester" onClick={this.handleClick}>Click Here Please</div>;
  }
});

这样做: -

  1. 通过添加“ref”属性来更改元素。

    div style={{backgroundColor: "red", fontSize: '5em'}} data-sortorder="asc" ref="tester" onClick={this.handleClick}
    
  2. 然后获取该属性:this.refs.tester.getAttribute("data-sortorder")

  3. OR OR ORIGINAL REQUEST,无REFS:

    1. 或者每个“特定事件” - 它正确地引用它如下: event.target.getAttribute("data-sortorder");