React: how to pass parameter in click event when I am binding this in the constructor?

Created on 15 Jul 2016  路  1Comment  路  Source: facebook/react

I鈥檓 binding this to the class in the constructor
like this:
class Header extends Component{
constructor(props) {
super(props)
this.dosometing= this.dosometing.bind(this)
}
dosometing(id){
console.log(id)
}
}
and write code in render
onClick={() => this.dosometing(id)}

is right?

Most helpful comment

Your onClick event handler will be called with an argument that has the type of SyntheticEvent (https://facebook.github.io/react/docs/events.html). If you don't need the value of the click event and only need to call doSomething with id (which I assume is a bound variable in your render function), then yeah onClick={() => this.doSomething(id)} should be fine. However if you need to preventDefault, stopPropagation, or do something with the client event, then you can let your doSomething function take an extra parameter and write onClick={(e) => this.doSomething(e, id)} instead.

We use the issue tracker for bugs and feature requests; since this is not a bug, please use StackOverflow or discussion forums for questions. Feel free to leave a link to your StackOverflow question in this thread if necessary. Thanks!

>All comments

Your onClick event handler will be called with an argument that has the type of SyntheticEvent (https://facebook.github.io/react/docs/events.html). If you don't need the value of the click event and only need to call doSomething with id (which I assume is a bound variable in your render function), then yeah onClick={() => this.doSomething(id)} should be fine. However if you need to preventDefault, stopPropagation, or do something with the client event, then you can let your doSomething function take an extra parameter and write onClick={(e) => this.doSomething(e, id)} instead.

We use the issue tracker for bugs and feature requests; since this is not a bug, please use StackOverflow or discussion forums for questions. Feel free to leave a link to your StackOverflow question in this thread if necessary. Thanks!

Was this page helpful?
0 / 5 - 0 ratings