如何从React中的事件对象访问自定义属性?

JavaScript

老丝神无

2020-03-10

http://facebook.github.io/react/docs/jsx-gotchas.html所述,React能够呈现自定义属性

如果要使用自定义属性,则应在其前面加上data-。

<div data-custom-attribute="foo" />

那是个好消息,除了我找不到从事件对象访问它的方法,例如:

render: function() {
...
<a data-tag={i} style={showStyle} onClick={this.removeTag}></a>
...
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"]

这些都不起作用。

第521篇《如何从React中的事件对象访问自定义属性?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
NearItachi 2020.03.10

I do not know about React, but in the general case you can pass custom attributes like this:

1) define inside an html-tag a new attribute with data- prefix

data-mydatafield = "asdasdasdaad"

2) get from javascript with

e.target.attributes.getNamedItem("data-mydatafield").value 
Tom猿 2020.03.10

Try instead of assigning dom properties (which is slow) just pass your value as a parameter to function that actually create your handler:

render: function() {
...
<a style={showStyle} onClick={this.removeTag(i)}></a>
...
removeTag = (customAttribute) => (event) => {
    this.setState({inputVal: customAttribute});
}
神奇 2020.03.10

You can access data attributes something like this

event.target.dataset.tag
猿小小 2020.03.10
// 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>
SamStafan十三 2020.03.10

或者您可以使用闭包:

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 
}
神乐Tony 2020.03.10

从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}); 
}
西门小小 2020.03.10

为了帮助您以与您要求不同的方式获得期望的结果:

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android