Thomas Charlesworth
Thomas Charlesworth

Reputation: 1839

React Native undefined is not an object (evaluating 'this.onPressButton.bind')

For so "onPress={this.onPressButton.bind(this)}" cause my application to fail?

What can I do to fix it. I believe its something to do with (this) becoming unbinded or something?

I have a component called Login being rendered:

export default class Login extends Component {

constructor(props) {
    super(props);
    this.state = {
        id:'login'
    }
}

render() {
    return(
        <KeyboardAvoidingView behavior="padding" style={style.container}>
            <View style={style.logoContainer}>
                <StatusBar barStyle="light-content" />
                <Image style={style.logo} source={require('../../image/Octocat.png')} />
                <Text style={style.logoText}> A Github app using React Native by{"\n"} Thomas Charlesworth</Text>
            </View>
            <View style={style.formContainer}>
                <LoginForm />
            </View>
        </KeyboardAvoidingView>
    );
}
}

And a login form component:

export default class LoginForm extends Component {

onPressButton(){
    this.props.navigator.push({
        id: 'splash',
        passProps: {
        // Your Props
        }
    })
}

render() {
    return(
        <View style={style.container}>
            <TextInput 
                style={style.input} 
                placeholder="Username" 
                placeholderTextColor="rgba(255,255,255,0.5)"
                returnKeyType="next"
                autoCapitalize="none"
                autoCorrect={false}
                onSubmitEditing={()=> this.passwordInput.focus()}
            />
            <TextInput 
                style={style.input} 
                secureTextEntry 
                placeholder="Password" 
                placeholderTextColor="rgba(255,255,255,0.5)"
                returnKeyType="go"
                ref={(input) => this.passwordInput = input}
            />
            <TouchableOpacity 
                style={style.buttonContainer}
                onPress={this.onPressButton.bind(this)}
            > 
                <Text style={style.buttonText}>
                    LOGIN
                </Text>
            </TouchableOpacity>
        </View>
    );
}
}

Upvotes: 0

Views: 1239

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104479

Write it like this:

Pass a function from parent component:

<LoginForm update={this.update.bind(this)}>

navigate(data){
    this.props.navigator.push({data});
}

In Child component:

onPressButton(){
    let data = {
        /*data*/
    }
    this.props.navigate(data);
}

Upvotes: 1

Related Questions