diff --git a/docs/reusable-components.html b/docs/reusable-components.html index d50555622e..2a8168aa49 100644 --- a/docs/reusable-components.html +++ b/docs/reusable-components.html @@ -583,13 +583,14 @@ constructor(props) { super(props); this.state = {count: props.initialCount}; + this.tick = this.tick.bind(this); } tick() { this.setState({count: this.state.count + 1}); } render() { return ( - <div onClick={this.tick.bind(this)}> + <div onClick={this.tick}> Clicks: {this.state.count} </div> ); @@ -598,7 +599,25 @@ Counter.propTypes = { initialCount: React.PropTypes.number }; Counter.defaultProps = { initialCount: 0 };
Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.
Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>:
// You can use bind() to preserve `this`
+<div onClick={this.tick.bind(this)}>
+
+// Or you can use arrow functions
+<div onClick={() => this.tick()}>
+We recommend that you bind your event handlers in the constructor so they are only bound once for every instance:
+constructor(props) {
+ super(props);
+ this.state = {count: props.initialCount};
+ this.tick = this.tick.bind(this);
+}
+Now you can use this.tick directly as it was bound once in the constructor:
// It is already bound in the constructor
+<div onClick={this.tick}>
+This is better for performance of your application, especially if you implement shouldComponentUpdate() with a shallow comparison in the child components.
Unfortunately ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes. Instead, we're working on making it easier to support such use cases without resorting to mixins.