[RN] Bind event handler once per instance, not per render

This commit is contained in:
Lyubo Marinov 2017-07-19 16:26:27 -05:00
parent e7fc4739c4
commit 0b5431b795
2 changed files with 28 additions and 3 deletions

View File

@ -42,6 +42,33 @@ export default class AbstractToolbarButton extends Component {
underlayColor: React.PropTypes.any
};
/**
* Initializes a new {@code AbstractToolbarButton} instance.
*
* @param {Object} props - The React {@code Component} props to initialize
* the new {@code AbstractToolbarButton} instance with.
*/
constructor(props) {
super(props);
// Bind event handlers so they are only bound once per instance.
this._onClick = this._onClick.bind(this);
}
/**
* Handles clicking/pressing this {@code AbstractToolbarButton} by
* forwarding the event to the {@code onClick} prop of this instance if any.
*
* @protected
* @returns {*} The result returned by the invocation of the {@code onClick}
* prop of this instance if any.
*/
_onClick(...args) {
const { onClick } = this.props;
return onClick && onClick(...args);
}
/**
* Implements React's {@link Component#render()}.
*

View File

@ -38,9 +38,7 @@ class ToolbarButton extends AbstractToolbarButton {
const props = {};
'disabled' in this.props && (props.disabled = this.props.disabled);
'onClick' in this.props && (props.onPress = event => {
this.props.onClick(event);
});
'onClick' in this.props && (props.onPress = this._onClick);
'style' in this.props && (props.style = this.props.style);
'underlayColor' in this.props
&& (props.underlayColor = this.props.underlayColor);