Using event.target with React components

后端 未结 1 1099
攒了一身酷
攒了一身酷 2020-12-13 01:36

I am having some trouble with my project. Can anyone explain to me why I can\'t use the e.target to access anything other than className?

B

相关标签:
1条回答
  • 2020-12-13 02:22

    First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

    if you need pass argument to update method you can do it like this

    onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
    

    and get these arguments inside update method

    update(e, space, txt){
       console.log(e.target, space, txt);
    }
    

    Example


    event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

    <button 
      data-space="home" 
      className="home" 
      data-txt="Home" 
      onClick={ this.props.onClick } 
    /> 
      Button
    </button>
    
    onClick(e) {
       console.log(e.target.dataset.txt, e.target.dataset.space);
    }
    

    Example

    0 讨论(0)
提交回复
热议问题