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

How to access custom attributes from event object in React?

本文关键字:事件 对象 访问 自定义属性 React      更新时间:2024-03-13

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

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

<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"]

这些都不起作用。

event.target为您提供了本机 DOM 节点,然后您需要使用常规的 DOM API 来访问属性。以下是有关如何执行此操作的文档:使用数据属性。

你可以做event.target.dataset.tagevent.target.getAttribute('data-tag');任何一个都有效。

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

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方法轻松访问该映射。

或者

你可以使用闭包:

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 
}
// 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>
<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对我有用

从 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.currentTarget.getAttribute('data-tag')

您可以访问如下所示的数据属性

event.target.dataset.tag

如果有人试图在 React 中使用 event.target 并找到一个空值,那是因为 SyntheticEvent 替换了 event.target。SyntheticEvent 现在保存"currentTarget",例如在 event.currentTarget.getAttribute('data-username'(。

https://facebook.github.io/react/docs/events.html

看起来 React 这样做是为了它可以在更多浏览器上运行。您可以通过 nativeEvent 属性访问旧属性。

您可以简单地使用 event.target.dataset 对象 。这将为您提供具有所有数据属性的对象。

我不知道

React,但在一般情况下,您可以像这样传递自定义属性:

1( 在 HTML 标签中定义一个带有 data- 前缀的新属性

data-mydatafield = "asdasdasdaad"

2( 从 JavaScript 获取

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

尝试不要分配 dom 属性(这很慢(,只需将您的值作为参数传递给实际创建处理程序的函数:

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

我有用...在示例中,我的属性名为"attr"。

e.target.selectedOptions[0].attributes.attr.value

如果您有多个具有不同数据标签(年龄,姓名,电子邮件(的图标:

       <button
          data-label="name" 
          onMouseOver={handleValue}
          className="icon"
        >
          <FaUser />
        </button>

当鼠标悬停在图标上时,您可以通过访问data-label来更改标题

const handleValue = (e) => {
    // making sure mouse is over an icon
    if (e.target.classList.contains("icon")) {
      const newValue = e.target.dataset.label;
      setTitle(newValue);
      setValue(person[newValue]);
    }
  };

在 React 中,你不需要 html 数据,使用函数返回另一个函数;像这样,发送自定义参数非常简单,你可以访问自定义数据和事件。

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

我认为建议绑定所有需要使用此方法的方法.setState方法,该方法在构造函数内部的React.Component类中定义,在您的情况下,构造函数应该像

    constructor() {
        super()
        //This binding removeTag is necessary to make `this` work in the callback
        this.removeTag = this.removeTag.bind(this)
    }
    removeTag(event){
        console.log(event.target)
        //use Object destructuring to fetch all element values''
        const {style, dataset} = event.target
        console.log(style)
        console.log(dataset.tag)
    }
   render() {
   ...
      <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
   ...},

有关对象解构的更多参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring