Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

javascript - 如何从React中的事件对象访问自定义属性?(How to access custom attributes from event object in React?)

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

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

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

(如果要使用自定义属性,则应在其前面加上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 eg:

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

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

The element and data- property render in html fine.

(元素和data-属性以html格式呈现。)

Standard properties like style can be accessed as event.target.style fine.

(像style这样的标准属性可以作为event.target.style访问。)

Instead of event.target I tried:

(我试过而不是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"]

none of these worked.

(这些都没有奏效。)

  ask by andriy_sof translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

event.target gives you the native DOM node, then you need to use the regular DOM APIs to access attributes.

(event.target为您提供本机DOM节点,然后您需要使用常规DOM API来访问属性。)

Here are docs on how to do that: Using data attributes .

(以下是有关如何执行此操作的文档: 使用数据属性 。)

You can do either event.target.dataset.tag or event.target.getAttribute('data-tag') ;

(你可以做event.target.dataset.tagevent.target.getAttribute('data-tag') ;)

either one works.

(两者都有效。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...