单击后如何在 React Native 中禁用按钮

Ark*_*itz 5 native button reactjs react-native

我正在做一个巨大的项目,但我遇到了一些问题。

每次点击登录按钮,数据库连接都需要一段时间,如果这个按钮是一个警报,你点击多次,它也会多次显示警报。

这是按钮:

 <TouchableOpacity
              style={styles.submitButton}
              onPress={
                () => this.login(this.state.email, this.state.password)
              }>
              <Text style={styles.submitButtonText}>Login</Text>
 </TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)

我想在单击后禁用该按钮,以便警报错误仅出现一次。

这是我想放置代码以停用按钮的地方:

if (respo == 'Wrong name or password.') {
          alert("Wrong Username and Password.");
        } else {
          if (respo.user.uid > 0) {
            if (Object.values(respo.user.roles).indexOf("student user") > -1) {
              AsyncStorage.setItem("u_uid", respo.user.uid);
              alert("Login Successfull.");
              Actions.home();
            } else {
              alert("Only Student user is allowed to login.");
            }
          }
        }
Run Code Online (Sandbox Code Playgroud)

谢谢!

Kas*_*kas 4

好吧,最简单的逻辑可能是:

  1. 设置一个变量来跟踪登录过程是否正在进行,例如
    var loginInProcess = false。这可能应该在跟踪应用程序状态的某个父组件的状态中设置,但让我们保持简单。
  2. 在该onPress事件中,设置值loginInProcess = true
  3. 仅当未登录时才有条件地执行登录操作:

例如:

   onPress = {() => {

    if (!loginInProcess) {
        loginInProcess = true;
        this.login(this.state.email, this.state.password)
    } else {
        /*Login in process, do something else*/
    }}}>
Run Code Online (Sandbox Code Playgroud)
  1. 如果登录失败(您的第二个代码块),请重置变量:loginInProcess = false以便能够再次尝试“登录”。