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

Categories

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?

Below is the code from my entry point:

import React from 'react'
import ReactDOM from 'react-dom'
import Button from './Button'
import Menu from './Menu'

function test(e){
    console.log(e.target.ref)
 }

module.exports = class Content extends React.Component {
    constructor(props){
        super(props)
        this.state={content: ''}
    }

update(e){
    console.log(e.target.txt)

}

render (){
    return (
        <div id="lower">
            <div id="menu">
               <Menu onClick={this.update.bind(this)}/>
            </div>
            <div id="content">
                {this.state.content}
            </div>
        </div>
    )

  }
}

I am trying to access the setting in the Menu component, using the update method. See Menu below:

module.exports = class Menu extends React.Component {

    render (){
       return (
           <div>
               <Button space="home" className="home" txt="Home" onClick={this.props.onClick}/>

        </div>
       )

    }
}

I really want to know why I can access the txt and space value using e.target. I have read the documentation and looked for other sources but I have no answer yet, but I am hoping there is a way it can be done.

See Question&Answers more detail:os

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...