Binding with this in React Native

By | July 14, 2018
Questions:
     _onPressButton =(username) =>{
        // alert("bye")
        this.props.navigation.navigator('Loc');
      }

     loginuser = (username, password) =>{

        Parse.User.logIn(username, password, {
        success: (user) =>  {
          // Do stuff after successful login.
            // 
            this._onPressButton(username);
            alert("hello")

        },
        error: (user, error) => {
          // The login failed. Check error to see why.
          alert("Error: " + error.code + " " + error.message);
        }
       });
      }

    render(){
    let { username } = this.state.username;
    return(

        <View style= {styles.container}>
              <TextField
                  inputContainerStyle={{ justifyContent: 'center', marginTop:30,marginLeft:50, marginRight:50, }}
                  inputStyle={{textAlign: 'center',justifyContent: 'center', backgroundColor: 'rgba(255,255,255,0.5)'}}
                  titleTextStyle={{ textAlign: 'center',justifyContent: 'center', }}
                  label='Username'
                  value={this.state.username}
                  onChangeText={ (username) => this.setState({ username}) }
              />

              <TextField
                  inputContainerStyle={{ justifyContent: 'center', marginTop:0,marginLeft:50, marginRight:50, }}
                  inputStyle={{textAlign: 'center',justifyContent: 'center', backgroundColor: 'rgba(255,255,255,0.5)'}}
                  titleTextStyle={{ textAlign: 'center',justifyContent: 'center', }}
                  label='Password'
                  secureTextEntry={true}
                  value={this.state.password}
                  onChangeText={ (password) => this.setState({ password}) }
              />

            <View>
              <TouchableOpacity
                  style={styles.loginScreenButton}
                   // onPress={() => this._onPressButton()}
                   onPress={() => this.loginuser(this.state.username, this.state.password)}
                  underlayColor='#fff'>
               <Text 
               style={styles.loginText}> Login </Text>
              </TouchableOpacity>
            </View>

        </View>
      );
    }
  }
  export default Project = createStackNavigator({
    Login: { screen: Login },
    Loc: { screen: Loc}
});

UPDATE

I am able to call _onPressButton() from function loginuser(username,password) using arrow functions ‘=>’ but this.props.navigation.navigator(‘Loc’) is not working.
alert(“bye”) works okay but this.props.navigation.navigator(‘Loc’); doesn’t execute. Maybe because of binding ‘this’ . Can someone help me with that?

P.S ‘Loc’ just another class which renders current location and prints it.

Answers:

Leave a Reply

Your email address will not be published. Required fields are marked *