React能够呈现自定义属性,如 http://facebook.github.io/react/docs/jsx-gotchas.html中所述:
如果要使用自定义属性,则应在其前面加上data-.
这是个好消息,除了我找不到从事件对象访问它的方法,例如:
render: function() { ... ... removeTag: function(event) { this.setState({inputVal: event.target????}); },
元素和data-
属性在html中渲染很好.像标准属性一样style
可以访问event.target.style
.而不是event.target
我试过:
event.target.props.data.tag event.target.props.data["tag"] event.target.props["data-tag"] event.target.data.tag event.target.data["tag"] event.target["data-tag"]
这些都没有奏效.
或者你可以使用一个闭包:
render: function() { ... <a data-tag={i} style={showStyle} onClick={this.removeTag(i)}></a> ... }, removeTag: function (i) { return function (e) { // and you get both `i` and the event `e` }.bind(this) //important to bind function }
为了帮助您以与您提出的不同的方式获得理想的结果:
render: function() { ... <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a> ... }, removeTag: function(i) { // do whatever },
请注意bind()
.因为这是所有javascript,你可以做这样的方便的事情.我们不再需要将数据附加到DOM节点以便跟踪它们.
IMO比依赖DOM事件要干净得多.
2017年4月更新:这些天我会写onClick={() => this.removeTag(i)}
而不是.bind
这是我发现的最佳方式:
var attribute = event.target.attributes.getNamedItem('data-tag').value;
这些属性存储在"NamedNodeMap"中,您可以使用getNamedItem方法轻松访问它们.
// Method inside the component userClick(event){ let tag = event.currentTarget.dataset.tag; console.log(tag); // should return Tagvalue } // when render element <a data-tag="TagValue" onClick={this.userClick}>Click me</a>
从React v16.1.1(2017)开始,这是官方解决方案:https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers
TLDR: OP应该做:
render: function() { ... <a style={showStyle} onClick={(e) => this.removeTag(i, e)}></a> ... removeTag: function(i, event) { this.setState({inputVal: i}); }
event.target
为您提供本机DOM节点,然后您需要使用常规DOM API来访问属性.以下是有关如何执行此操作的文档:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes#JavaScript_Access
你可以做任何一个event.target.dataset.tag
或event.target.getAttribute('data-tag')
; 两者都有效.
<div className='btn' onClick={(e) => console.log(e.currentTarget.attributes['tag'].value)} tag='bold'> <i className='fa fa-bold' /> </div>
所以e.currentTarget.attributes['tag'].value
对我有用