I'm pretty new to react. I've noticed many people binding this
to their DOM's elements functions.
Let's say I have a component with:
render(){
<div>
<button onClick={this.doSomething.bind(this)} test={someObj}></button>
</div>
}
doSomething(){
this.props.whatever();
}
Now, In my mind it made sense having this
bound to this.doSomething
, because otherwise this
would be the button component object, and the this.props would be relative to the button's props, which is something I don't want.
So I got caught in a situation where I wanted to get something from the button's props (the test
object). What I thought I could do: remove the bind(this)
from the call, so this.props
would be the button's props. But when I call this.doSomething
without using bind, this
is returning null (maybe I'm messing this up somehow).
I guess my logic is flawed then. I would like to know what's the real purpose of binding this
to the handlers and if there's a way that I can access a DOM element's props (or at least, how can I get the test
in the example)
The click handler gets passed a SyntheticEvent and you can access the DOM node via that event
doSomething(event) {
console.log(event.target.getAttribute('data-test'));
}
Alternatively you can give the DOM element a reference
<button data-test={someObj} ref="myButton" />
and access that as
doSomething() {
console.log(this.refs.myButton)
}
But really, you shouldn't use the DOM as a database, and rather store any data for later in your component's state.
EDIT:
For the usecase explained in the comments here I'd do something like this:
class MyButton extends React.Component {
handleClick() {
this.props.foo(this.props.id);
}
render() {
return (
<div>
<button
onClick={this.handleClick.bind(this)}
>
Click {this.props.id}
</button>
</div>
);
}
}
class TestComponent extends React.Component {
foo(id) {
console.log(id);
}
render() {
const objs = [{id:1},{id:2}];
return (
<div>
{objs.map(obj => (<MyButton key={obj.id} id={obj.id} foo={this.foo}/>))}
</div>
);
}
}
Here we've made a custom component for the button and are keeping our data away from the DOM and in that component's props instead.
You can store data-value in button as follows:
render(){
<div>
<button data-value="item1" onClick={this.doSomething.bind(this)} test={someObj}></button>
</div>
}
And access using this:
doSomething(event){
console.log(event.target.dataset.value)
this.props.whatever();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.