Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto binding doesn't work with ES6-style components #814

Closed
grgur opened this issue Apr 11, 2015 · 1 comment
Closed

Auto binding doesn't work with ES6-style components #814

grgur opened this issue Apr 11, 2015 · 1 comment
Labels
Resolution: Locked This issue was locked by the bot.

Comments

@grgur
Copy link

grgur commented Apr 11, 2015

When creating a component 'ES6-style' (e.g. class Card extends React.Component), event callbacks will not automatically bind scope.

In the following example, I had to replace
onPress={this.onPress}
with
onPress={this.onPress.bind(this)}.

Using React Native 0.3.11

class Card extends React.Component {
    constructor(properties) {
        super(properties);
        this.state = {
            paired: false,
            visible: false
        };
    }

   onPress() {
        var state = this.state;
        console.log("I am no longer null", state);
    }
    render() {
        return (
          <TouchableHighlight
            onPress={this.onPress.bind(this)}
            underlayColor="blue"
            activeOpacity={0.5}>
            <Text>Dummy Text</Text>
          </TouchableHighlight>
        );
    }
};
@sophiebits
Copy link
Contributor

This is expected behavior. In ES7 you'll likely be able to use a property initializer to write

onPress = () => {
  // ...
}

which will autobind. This syntax is supported by Babel already in an experimental transform and hopefully will be supported in react-native sometime. You can continue to use React.createClass if you prefer its semantics.

@facebook facebook locked as resolved and limited conversation to collaborators May 29, 2018
@react-native-bot react-native-bot added the Resolution: Locked This issue was locked by the bot. label Jul 22, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Resolution: Locked This issue was locked by the bot.
Projects
None yet
Development

No branches or pull requests

3 participants