How to access custom attributes from event object in React?

前端 未结 15 1926
不思量自难忘°
不思量自难忘° 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 10:02
    <div className='btn' onClick={(e) =>
         console.log(e.currentTarget.attributes['tag'].value)}
         tag='bold'>
        <i className='fa fa-bold' />
    </div>
    

    so e.currentTarget.attributes['tag'].value works for me

    0 讨论(0)
  • 2020-11-27 10:02

    As of React v16.1.1 (2017), here is the official solution: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

    TLDR: OP should do:

    render: function() {
    ...
    <a style={showStyle} onClick={(e) => this.removeTag(i, e)}></a>
    ...
    removeTag: function(i, event) {
        this.setState({inputVal: i}); 
    }
    
    0 讨论(0)
  • 2020-11-27 10:04
    // 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>
    
    0 讨论(0)
  • 2020-11-27 10:07

    You can access data attributes something like this

    event.target.dataset.tag
    
    0 讨论(0)
  • 2020-11-27 10:11

    I think it's recommended to bind all methods where you need to use this.setState method which is defined in the React.Component class, inside the constructor, in your case you constructor should be like

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

    For more reference on Object destructuring https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

    0 讨论(0)
  • 2020-11-27 10:12

    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});
    }
    
    0 讨论(0)
提交回复
热议问题