Using ES5 development with ReactJS, a component can be specified as follows:
var MyComponent = React.createClass({ alertSomething: function(event) { alert(event.target); }, render: function() { return ( <button onClick={this.alertSomething}>Click Me!</button> ); } }); ReactDOM.render(<MyComponent />);
In this example, this refers to the object itself, which is the expected natural behavior.
Question
My question is:
How do you use ES6 to create components?
class MyComponent extends React.Component { constructor(props) { super(props); } alertSomething(event) { alert(event.target); } render() { return ( <button onClick={this.alertSomething.bind(this)}>Click Me!</button> ); } } ReactDOM.render(<MyComponent />);
Knowing that in JavaScript this refers to the instance of the object itself when using the new operator, can someone tell me what is the real purpose of using bind? Is this something related to the internal mechanisms of React?
javascript reactjs bind
Francisco Maria Calisto
source share