使用状态覆盖按钮backgroundColor

时间:2020-07-09 01:54:39

标签: react-native

如果所有输入字段均已填写,我尝试更改“继续”按钮backgroundColor 我似乎无法改变 我这样做的方式,它不会覆盖backgroundColor并且不会更改状态 这是我的代码:

import React, { Component } from "react";
import firebase from "../util/firebase";
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  TextInput,
  ActivityIndicator,
  Alert,
} from "react-native";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from "react-native-responsive-screen";

export default class Register extends React.Component {
  //State Constructor
  constructor() {
    super();
    this.state = {
      confirmPassword: "",
      email: "",
      password: "",
      isLoading: false,
      buttonColor: "#8b898a",
    };
  }
  //Change Button Color
  changeColor() {
    let currentColor = this.state.buttonColor;
    if (
      this.state.email != "" &&
      this.state.password != "" &&
      this.state.confirmPassword != ""
    ) {
      currentColor = "#7356bf";
    } else currentColor = "#8b898a";
    this.setState({ buttonColor: currentColor });
  }
  //Update Input State to Current Input Value
  updateInputVal = (val, prop) => {
    const state = this.state;
    state[prop] = val;
    this.setState(state, () => changeColor());
  };
  //Register Function
  registerUser = () => {
    //If Input Blank Return Alert
    if (this.state.email === "" && this.state.password === "") {
      Alert.alert("Enter details to signup!");
    }
    //If Passwords Dont Match Return Alert
    else if (this.state.password !== this.state.confirmPassword) {
      Alert.alert("Passwords Don't Match");
    }
    //If Everything OK Register User
    else {
      this.setState({
        isLoading: true,
      });
      firebase
        //Activate Auth
        .auth()
        //New Function
        //Create New User
        .createUserWithEmailAndPassword(
          this.state.email,
          this.state.password
          // this.state.confirmPassword
        )
        //After Creating User
        .then(() => {
          console.log("User registered successfully!");
          this.setState({
            isLoading: false,
            email: "",
            password: "",
            // confirmPassword: "",
          });
          //Something To Do After Everything Finished, for Example: this.props.navigation.navigate('Next Screen')
        })
        .catch(function (error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          if (errorCode == "auth/weak-password") {
            alert("The password is too weak.");
          } else if (errorCode == "auth/invalid-email") {
            alert("Email is Invalid");
          } else if (errorCode == "auth/email-already-in-use") {
            alert("Email is Already in use!");
          } else {
            alert(errorMessage);
          }
          console.log(error);
        });
    }
  };

  render() {
    if (this.state.isLoading) {
      return (
        <View style={styles.preloader}>
          <ActivityIndicator size="large" color="#9E9E9E" />
        </View>
      );
    }
    return (
      <View style={styles.container}>
        <View style={styles.titleContainer}>
          <Text style={styles.title}>
            Create an account and join our studio
          </Text>
        </View>
        <View style={styles.inputsContainer}>
          <TextInput
            style={styles.emailInput}
            placeholder="Email"
            value={this.state.email}
            onChangeText={(val) => this.updateInputVal(val, "email")}
          />
          <TextInput
            style={styles.passwordInput}
            placeholder="Password"
            value={this.state.password}
            onChangeText={(val) => this.updateInputVal(val, "password")}
            maxLength={15}
            secureTextEntry={true}
          />
          <TextInput
            style={styles.confirmPasswordInput}
            placeholder="ConfirmPassword"
            value={this.state.confirmPassword}
            onChangeText={(val) => this.updateInputVal(val, "confirmPassword")}
            maxLength={15}
            secureTextEntry={true}
          />
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity
            style={[
              styles.loginButton,
              { backgroundColor: this.state.buttonColor },
            ]}
            title="Continue"
            onPress={() => this.registerUser()}
          >
            <Text style={styles.loginText}>Continue</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  //Views
  container: {
    flex: 1,
    backgroundColor: "#ffffff",
  },
  titleContainer: {
    height: hp(10),
    width: wp(65.2),
    alignItems: "center",
    marginLeft: wp(17.4),
    marginRight: wp(17.4),
    marginTop: hp(17.1),
  },
  inputsContainer: {
    marginTop: hp(7.9),
    alignItems: "center",
  },
  buttonContainer: {
    alignItems: "center",
  },
  //Button
  loginButton: {
    flexDirection: "row",
    marginTop: hp(14),
    alignItems: "center",
    justifyContent: "center",
    borderRadius: 32.5,
    width: wp(78.3),
    height: hp(7.3),
    backgroundColor: "grey",
  },
  //Inputs
  emailInput: {
    height: hp(5.4),
    width: wp(65.2),
    borderBottomColor: "grey",
    borderBottomWidth: 1,
  },
  passwordInput: {
    height: hp(5.4),
    width: wp(65.2),
    marginTop: hp(6.3),
    borderBottomColor: "grey",
    borderBottomWidth: 1,
  },
  confirmPasswordInput: {
    height: hp(5.4),
    width: wp(65.2),
    marginTop: hp(6.3),
    borderBottomColor: "grey",
    borderBottomWidth: 1,
  },
  //Title
  title: {
    flex: 1,
    textAlign: "center",
    fontSize: hp(3.8),
  },
  //Loading
  preloader: {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    position: "absolute",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#fff",
  },
});

有什么主意我做错了吗? 如果有人知道答案,请彻底解释它,因为我是编码新手。

更新:在updateInputVal内调用函数changeColor后,出现错误“ ReferenceError:找不到变量:changeColor”

2 个答案:

答案 0 :(得分:1)

您必须进行一些更改:

1。原始状态颜色:

constructor() {
    super();
    this.state = {
      confirmPassword: "",
      email: "",
      password: "",
      isLoading: false,
      buttonColor: "#8b898a",  // to gray  
    };
}
  1. updateInputVal()中添加更改颜色功能
updateInputVal = (val, prop) => {
    const state = this.state;
    state[prop] = val;
    this.setState(state);
    this.changeColor();  // Here ++
  };
  1. 更改状态名称并包装[]
<TouchableOpacity
  style={
    [styles.loginButton,{backgroundColor: this.state.buttonColor}]  //this line  () to [] , not currentColor is buttonColor
  }
  title="Continue"
  onPress={() => this.registerUser()}
>
<Text style={styles.loginText}>Continue</Text>
</TouchableOpacity>

这是我在sandBox上创建的示例

答案 1 :(得分:0)

在此代码中,您不会在任何地方调用changeColor函数。

您可以在输入文本更改时调用它(updateInputVal函数)。

this.setState(state, () => this.changeColor());