函数被自动调用,无法按预期工作

时间:2017-05-30 09:42:19

标签: react-native

我尝试使用React Native创建应用程序。我有一个注册页面,但它不起作用。 我有一个名为checkPassword的方法来查看用户编写的密码和验证密码是否相同:

checkPassword(){
    console.log("inside checkPassword");
    if (this.state.password == this.state.verify) {
      console.log("inside if check...");
      this.handlePress;
    }else{
      console.log("password not match.");
    }
  }

问题是在日志中我可以看到当我到达注册页面时会自动调用该函数。这是日志:

RegisterScreen.js:23 inside checkPassword
RegisterScreen.js:25 inside if check...
RegisterScreen.js:23 inside checkPassword
RegisterScreen.js:25 inside if check...
RegisterScreen.js:23 inside checkPassword
RegisterScreen.js:25 inside if check...

它继续......

一旦我进入注册页面就会出现,加上,this.handlePress没有被调用。这是handlePress:

 handlePress(){
    firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then(function(newUser){
      //good
      console.log("good")
    }).catch(function(error){
      //bad
      console.log("bad")
    });
  }

在这里我调用checkPassword函数:

<TouchableOpacity style={styles.subButtom} onPress={this.checkPassword}>
  <Text style={styles.subTxt}>
  Register
  </Text>
  </TouchableOpacity>

我做错了什么?

2 个答案:

答案 0 :(得分:1)

试试这个:

checkPassword(){
  console.log("inside checkPassword");
  if (this.state.password == this.state.verify) {
    console.log("inside if check...");
    this.handlePress();
  }else{
    console.log("password not match.");
  }
}

并尝试将onPress改为:

<TouchableOpacity style={styles.subButtom} onPress={() => this.checkPassword()}>

答案 1 :(得分:0)

尝试

checkPassword(){
    console.log("inside checkPassword");
    if (this.state.password == this.state.verify) {
      console.log("inside if check...");
      return this.handlePress();
    }else{
      console.log("password not match.");
    }
  }