如何从 React 中的事件对象访问自定义属性? [英] How to access custom attributes from event object in React?

查看:28
本文介绍了如何从 React 中的事件对象访问自定义属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

React is able to render custom attributes as described at http://facebook.github.io/react/docs/jsx-gotchas.html:

如果你想使用自定义属性,你应该给它加上前缀数据-.

If you want to use a custom attribute, you should prefix it with data-.

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

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

And that's great news except I can't find a way to access it from the event object e.g.:

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 我试过:

The element and data- property render in html fine. Standard properties like style can be accessed as event.target.style fine. Instead of event.target I tried:

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

这些都没有用.

推荐答案

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

To help you get the desired outcome in perhaps a different way than you asked:

render: function() {
    ...
    <a data-tag={i} style={showStyle} onClick={this.removeTag.bind(null, i)}></a>
    ...
},
removeTag: function(i) {
    // do whatever
},

注意bind().因为这都是 javascript,所以你可以做这样的方便的事情.我们不再需要将数据附加到 DOM 节点以跟踪它们.

Notice the bind(). Because this is all javascript, you can do handy things like that. We no longer need to attach data to DOM nodes in order to keep track of them.

IMO 这比依赖 DOM 事件要干净得多.

IMO this is much cleaner than relying on DOM events.

2017 年 4 月更新:这些天我会写 onClick={() =>this.removeTag(i)} 而不是 .bind

Update April 2017: These days I would write onClick={() => this.removeTag(i)} instead of .bind

这篇关于如何从 React 中的事件对象访问自定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆