How to access custom attributes from event object in React?

前端 未结 15 1925
不思量自难忘°
不思量自难忘° 2020-11-27 09:27

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 attribut

相关标签:
15条回答
  • 2020-11-27 09:51

    Here's the best way I found:

    var attribute = event.target.attributes.getNamedItem('data-tag').value;
    

    Those attributes are stored in a "NamedNodeMap", which you can access easily with the getNamedItem method.

    0 讨论(0)
  • 2020-11-27 09:53

    event.target gives you the native DOM node, then you need to use the regular DOM APIs to access attributes. 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'); either one works.

    0 讨论(0)
  • 2020-11-27 09:53

    This single line of code solved the problem for me:

    event.currentTarget.getAttribute('data-tag')
    
    0 讨论(0)
  • 2020-11-27 09:55

    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
    },
    

    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 this is much cleaner than relying on DOM events.

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

    0 讨论(0)
  • 2020-11-27 09:59

    Or you can use a closure :

    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 
    }
    
    0 讨论(0)
  • 2020-11-27 10:01

    In React you don't need the html data, use a function return a other function; like this it's very simple send custom params and you can acces the custom data and the event.

    render: function() {
    ...
    <a style={showStyle} onClick={this.removeTag(i)}></a>
    ...
    removeTag: (i) => (event) => {
        this.setState({inputVal: i}); 
    },
    
    0 讨论(0)
提交回复
热议问题