Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Using event.target with React components

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...