Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native access this.prop from inside function

Tags:

react-native

I have the following code:

module.exports = class Menu extends Component {

    about() {
        this.props.nav.push({
            component: TestView,
            title: 'Test View',
        });
    }

    render() {
        return (
            <ScrollView
                scrollsToTop={false}
                style={styles.menu}
                navigator={this.props.nav}>
                <View style={styles.logoContainer}>
                    <Image
                        style={styles.logo}
                        source={{ uri, }}/>
                </View>

                <Text onPress={this.about} style={styles.item}>About</Text>
                <Text style={styles.item}>Account</Text>
            </ScrollView>
        );
    }
};

I keep getting the error message:

"undefined is not an object ("evaluating this.props.nav") 

when "onPress" calls "this.about". I placed a console.log within the render function and I could see that this.props.nav contained a value. The issue occurs in the about() function and I am not sure why.

Any suggestions would be great?

Thanks

like image 484
samb90 Avatar asked Jan 26 '16 21:01

samb90


1 Answers

I can't be certain, but this looks like a Javascript this binding problem to me. In ReactJS components defined with the ES6 class syntax do not automatically bind this, so you're being bitten by Javascript's rules that vary the value of this depending on how a function is called.

You may need to explicitly use .bind when setting your button handler:

<Text onPress={this.about.bind(this)} style={styles.item}>About</Text>

So that this in the about() function will be the same as the this in the render() function where you set up the handler.

I found a repo which shows other methods of solving the same problem, like binding in a constructor or using "Fat-arrow" functions for your handler.

My experience is with using React for web, and I'm not sure if React Native differs in this area.

like image 52
matts Avatar answered Oct 29 '22 16:10

matts