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.
To use the addEventListener method in function components in React: Set the ref prop on the element. Use the current property on the ref to get access to the element. Add the event listener in the useEffect hook.
Adding Events React events are written in camelCase syntax: onClick instead of onclick . React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()" .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With