【问题标题】:how can i convert this following code class to function component如何将以下代码类转换为功能组件
【发布时间】:2022-01-24 08:58:27
【问题描述】:

在这里,我从我的商店文件夹中导入了一些其他文件,此屏幕用于 pin 身份验证。

import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  Dimensions,
} from "react-native";
import AppStore from "../../stores/AppStore";
import Theme from "../../utils/Theme";
import { Observer } from "mobx-react";
import Iconpack from "../../utils/Iconpack";
import FastImage from "react-native-fast-image";
import { Screen } from "../CommonComponent/Screen";
import PinAuthenticationStore from "../../stores/PinAuthenticationStore";
import Toast from "react-native-simple-toast";
import Header from "../CommonComponent/Header";

const hRem = AppStore.screenHeight / 812;
const wRem = AppStore.screenWidth / 375;

class PinAuthentication extends Component {
  constructor(props) {
    super(props);
    this.state = {
      passcode: ["", "", "", ""],
      pin: "",
      confirmThePin: false,
      reconfirmPin: "",
    };
  }

  showToast = () => {
    // ToastAndroid.show("Pick Enter Valid Pin !", ToastAndroid.SHORT);
    Toast.show("Please Enter Valid Pin !", Toast.LONG);
  };

  onPressNumber = (num) => {
    let tempCode = this.state.passcode;
    for (var i = 0; i < tempCode.length; i++) {
      if (tempCode[i] == "") {
        tempCode[i] = num;
        if (this.state.confirmThePin) {
          this.setState({ reconfirmPin: this.state.reconfirmPin + num });
        } else {
          this.setState({ pin: this.state.pin + num });
        }
        break;
      } else {
        continue;
      }
    }
    this.setState({ passcode: tempCode });
  };

  onPressCancel = () => {
    let tempCode = this.state.passcode;
    for (var i = tempCode.length - 1; i >= 0; i--) {
      if (tempCode[i] != "") {
        tempCode[i] = "";
        this.setState({
          pin: this.state.pin.slice(0, i),
          reconfirmPin: this.state.reconfirmPin.slice(0, i),
        });
        break;
      } else {
        continue;
      }
    }
    // if(tempCode.length==0){
    console.log("cancel", tempCode);
    // }
    this.setState({ passcode: tempCode });
  };

  reset = () => {
    this.setState({
      passcode: ["", "", "", ""],
      confirmThePin: false,
      reconfirmPin: "",
      pin: "",
    });
  };

  confirmPin = () => {
    if (AppStore.idExist) {
      if (this.state.pin == AppStore.userPin) {
        this.props.navigation.navigate("MainAdd");
        this.reset();
        // AppStore.setFields("isNewUserPin", true);
      } else {
        this.showToast();
        this.setState({ passcode: ["", "", "", ""], pin: "" });
        // AppStore.setFields("isNewUserPin", false);
      }
    } else if (this.state.pin == this.state.reconfirmPin) {
      // console.log("new user");
      PinAuthenticationStore.setPinForNewUser(this.state.reconfirmPin);
      // PinAuthenticationStore.setUserPin(this.state.reconfirmPin)
      PinAuthenticationStore.setStringIsLoggedIn("true");
      this.reset();
      this.props.navigation.navigate("MainAdd");
      // AppStore.setFields("isNewUserPin", true);
    } else if (
      this.state.pin != this.state.reconfirmPin &&
      this.state.reconfirmPin.length > 0
    ) {
      this.setState({
        passcode: ["", "", "", ""],
        confirmThePin: false,
        reconfirmPin: "",
        pin: "",
      });
      this.showToast();
      // AppStore.setFields("isNewUserPin", false);
    } else {
      if (this.state.pin.length == 4 && !this.state.confirmThePin) {
        this.setState({ passcode: ["", "", "", ""], confirmThePin: true });
      } else if (this.state.reconfirmPin.length == 4) {
        this.setState({ passcode: ["", "", "", ""] });
      }
      // AppStore.setFields("isNewUserPin", false);
    }

    console.log("confirm pin", this.state.pin, AppStore.userPin);
  };

  render() {
    let numbers = [
      { id: 1 },
      { id: 2 },
      { id: 3 },
      { id: 4 },
      { id: 5 },
      { id: 6 },
      { id: 7 },
      { id: 8 },
      { id: 9 },
      {
        id: 10,
      },
      { id: 0 },
      {
        id: 11,
      },
    ];
    return (
      <Observer>
        {() => (
          <>
            {/* <Screen
              style={{ flex: 1 }}
              statusBar={"light-content"}
              variant={true}
              showMenu={false}
              onNavigate={this.props.navigation}
            > */}
            <FastImage
              style={styles.container}
              source={Iconpack.PIN_SCREEN_BG}
              resizeMode={FastImage.resizeMode.cover}
            />
            <Header
              headerText="Set new PIN"
              onPress={() => {
                this.props.navigation.navigate("WalkThrough");
              }}
            />
            <View>
              <Text style={styles.pinConfirmationText}>
                {AppStore.idExist
                  ? `Enter current PIN`
                  : this.state.confirmThePin
                  ? `Re-confirm PIN`
                  : `Enter new PIN`}
              </Text>
            </View>
            <View style={styles.codeContainer}>
              {this.state.passcode.map((p, i) => {
                console.log("xxxx", p);
                let style = p != "" ? styles.inputBox1 : styles.inputBox;
                let passMask = p != "" ? "*" : "";
                return (
                  <View style={style} key={i}>
                    <Text style={styles.inputText}>{passMask}</Text>
                  </View>
                );
              })}
            </View>

            <View style={styles.mod0}>
              <View style={styles.numberContainer}>
                {numbers.map((num, numb) => {
                  return (
                    <>
                      {num.id == 10 ? (
                        <TouchableOpacity
                          key={num.id.toString()}
                          onPress={() => this.onPressCancel()}
                          style={
                            AppStore.isiOS ? styles.number : styles.number2
                          }
                        >
                          <Image
                            style={styles.img}
                            source={Iconpack.PIN_CANCEL}
                          />
                        </TouchableOpacity>
                      ) : num.id == 11 ? (
                        <TouchableOpacity
                          key={num.id.toString()}
                          onPress={() => {
                            this.confirmPin();
                          }}
                          style={
                            AppStore.isiOS ? styles.number : styles.number2
                          }
                        >
                          <Image
                            style={styles.img}
                            source={Iconpack.PIN_CHECK}
                          />
                        </TouchableOpacity>
                      ) : (
                        <TouchableOpacity
                          key={num.id.toString()}
                          onPress={() => this.onPressNumber(num.id.toString())}
                          style={
                            AppStore.isiOS ? styles.number : styles.number2
                          }
                        >
                          <Text style={styles.numberText}>
                            {num.id.toString()}
                          </Text>
                        </TouchableOpacity>
                      )}
                    </>
                  );
                })}
              </View>
            </View>
            {/* </Screen> */}
          </>
        )}
      </Observer>
    );
  }
}

export default PinAuthentication;

const styles = StyleSheet.create({
  mod0: { alignItems: "center", justifyContent: "center" },
  container: {
    flex: 1,
    position: "absolute",
    top: 0,
    right: 0,
    left: 0,
    bottom: 0,
    backgroundColor: "#021831",
  },
  pinConfirmationText: {
    textAlign: "center",
    marginTop: hRem * 44,
    color: "white",
    ...Theme.encodeSansMed3,
    lineHeight: hRem * 19.07,
  },
  borderStyleBase: {
    width: 30,
    height: 45,
  },

  borderStyleHighLighted: {
    borderColor: "#707070",
  },

  underlineStyleBase: {
    width: wRem * 62,
    height: 45,
    borderWidth: 0,
    borderBottomWidth: 1,
  },

  underlineStyleHighLighted: {
    borderColor: "#FFFFFF",
  },
  number: {
    borderRadius:
      Math.round(
        Dimensions.get("window").width + Dimensions.get("window").height
      ) / 2,
    width: Dimensions.get("window").width * 0.2,
    height: Dimensions.get("window").width * 0.2,
    backgroundColor: "#000000",
    justifyContent: "center",
    alignItems: "center",
    marginHorizontal: wRem * 12,
    marginVertical: hRem * 9,
  },
  number2: {
    borderRadius:
      Math.round(
        Dimensions.get("window").width + Dimensions.get("window").height
      ) / 2,
    width: Dimensions.get("window").width * 0.2,
    height: Dimensions.get("window").width * 0.2,
    backgroundColor: "#000000",
    justifyContent: "center",
    alignItems: "center",
    marginHorizontal: wRem * 12,
    marginVertical: hRem * 9,
    shadowColor: "rgba(27, 100, 206, 0.8)",
    shadowOffset: {
      width: 1,
      height: 5,
    },
    shadowOpacity: 1.5,
    shadowRadius: 5,

    elevation: 10,
  },
  numberContainer: {
    flexDirection: "row",
    flexWrap: "wrap",
    marginTop: hRem * 99,
    alignItems: "center",
    justifyContent: "center",
    shadowColor: Theme.shadow_Button,
    shadowOffset: {
      width: 1,
      height: 1,
    },
    shadowOpacity: 1.5,
    shadowRadius: 5,

    elevation: 3,
  },

  numberText: {
    ...Theme.encodeSansMed4,
    // lineHeight: hRem * 16,
    // position: "absolute",
    textAlign: "center",
    color: Theme.white_color,
  },
  codeContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginHorizontal: wRem * 49,
    marginTop: hRem * 50,
  },
  inputBox: {
    width: wRem * 62,
    borderBottomWidth: 1,
    borderColor: "#707070",
    alignItems: "center",
    justifyContent: "space-between",
  },
  inputBox1: {
    width: wRem * 62,
    borderBottomWidth: 1,
    borderColor: "#FFFFFF",
    alignItems: "center",
    justifyContent: "space-between",
  },
  inputText: {
    color: "white",
    ...Theme.encodeSansMed3,
    marginBottom: hRem * 21,
  },
  img: {
    width: wRem * 30,
    height: hRem * 22,
  },
});

在这里我已经上传了我需要在类组件中转换为函数组件的整个代码,对于整个代码我是 react-native 的新手,请指导我并帮助我,提前谢谢

【问题讨论】:

  • 如果您自己点击几下,您将了解更多信息,以下是可以帮助您的简单指南。 link

标签: javascript android ios reactjs react-native


【解决方案1】:

您的组件现在将是这个 ..

import React, { useState } from "react";
import {
     StyleSheet,
     Text,
     View,
     Image,
     TouchableOpacity,
     Dimensions,
     } from "react-native";
import AppStore from "../../stores/AppStore";
import Theme from "../../utils/Theme";
import { Observer } from "mobx-react";
import Iconpack from "../../utils/Iconpack";
import FastImage from "react-native-fast-image";
import PinAuthenticationStore from "../../stores/PinAuthenticationStore";
import Toast from "react-native-simple-toast";
import Header from "../CommonComponent/Header";

const hRem = AppStore.screenHeight / 812;
const wRem = AppStore.screenWidth / 375;

function PinAuthentication (props) {
  const [passcode,setPassCode] = useState(["", "", "", ""]);
  const [pin,setPin] = useState("");
  const [confirmThePin,setConfirmThePin] = useState(false);
  const [reconfirmPin,setReconfirmPin] = useState('')


 const showToast = () => {
   // ToastAndroid.show("Pick Enter Valid Pin !", ToastAndroid.SHORT);
   Toast.show("Please Enter Valid Pin !", Toast.LONG);
 };

 const  onPressNumber = (num) => {
  let tempCode = passcode;
  for (var i = 0; i < tempCode.length; i++) {
    if (tempCode[i] == "") {
      tempCode[i] = num;
      if (confirmThePin) {
      setReconfirmPin(reconfirmPin + num);
    } else {
      setPin(pin + num);
    }
    break;
   } else {
       continue;
   }
 }
    setPassCode(tempCode)
 };

const onPressCancel = () => {
let tempCode = passcode;
for (var i = tempCode.length - 1; i >= 0; i--) {
  if (tempCode[i] != "") {
    tempCode[i] = "";
    setPin(pin.slice(0,i));
    setReconfirmPin(reconfirmPin.slice(0,i))
    break;
  } else {
    continue;
  }
 }
// if(tempCode.length==0){
console.log("cancel", tempCode);
// }
setPassCode(tempCode)
};

const reset = () => {
   setPassCode(["","","",""])
   setConfirmThePin(false);
   setReconfirmPin("");
   setPin("");
 };

 const confirmPin = () => {
 if (AppStore.idExist) {
  if (pin == AppStore.userPin) {
    props.navigation.navigate("MainAdd");
    reset();
    // AppStore.setFields("isNewUserPin", true);
  } else {
    showToast();
    setPassCode(["","","",""])
    setPin("");
    // AppStore.setFields("isNewUserPin", false);
  }
  } else if (pin == reconfirmPin) {
  // console.log("new user");
  PinAuthenticationStore.setPinForNewUser(reconfirmPin);
  // PinAuthenticationStore.setUserPin(this.state.reconfirmPin)
  PinAuthenticationStore.setStringIsLoggedIn("true");
  reset();
  props.navigation.navigate("MainAdd");
  // AppStore.setFields("isNewUserPin", true);
} else if (
  pin != reconfirmPin &&
  reconfirmPin.length > 0
) {
  setPassCode(["","","",""])
  setConfirmThePin(false);
  setReconfirmPin("");
  setPin("");
  showToast();
  // AppStore.setFields("isNewUserPin", false);
 } else {
  if (pin.length == 4 && !confirmThePin) {
    setPassCode(["","","",""])
    setConfirmThePin(true);

  } else if (reconfirmPin.length == 4) {
    setPassCode(["","","",""])
  }
  // AppStore.setFields("isNewUserPin", false);
  }

    console.log("confirm pin", pin, AppStore.userPin);
  };

 const numbers = [
  { id: 1 },
  { id: 2 },
  { id: 3 },
  { id: 4 },
  { id: 5 },
  { id: 6 },
  { id: 7 },
  { id: 8 },
  { id: 9 },
  {
    id: 10,
  },
  { id: 0 },
  {
    id: 11,
  },
];
return (
  <Observer>
    {() => (
      <>
        <FastImage
          style={styles.container}
          source={Iconpack.PIN_SCREEN_BG}
          resizeMode={FastImage.resizeMode.cover}
        />
        <Header
          headerText="Set new PIN"
          onPress={() => {
            props.navigation.navigate("WalkThrough");
          }}
        />
        <View>
          <Text style={styles.pinConfirmationText}>
            {AppStore.idExist
              ? `Enter current PIN`
              : confirmThePin
              ? `Re-confirm PIN`
              : `Enter new PIN`}
          </Text>
        </View>
        <View style={styles.codeContainer}>
          {passcode.map((p, i) => {
            console.log("xxxx", p);
            let style = p != "" ? styles.inputBox1 : styles.inputBox;
            let passMask = p != "" ? "*" : "";
            return (
              <View style={style} key={i}>
                <Text style={styles.inputText}>{passMask}</Text>
              </View>
            );
          })}
        </View>

        <View style={styles.mod0}>
          <View style={styles.numberContainer}>
            {numbers.map((num, numb) => {
              return (
                <>
                  {num.id == 10 ? (
                    <TouchableOpacity
                      key={num.id.toString()}
                      onPress={() => onPressCancel()}
                      style={
                        AppStore.isiOS ? styles.number : styles.number2
                      }
                    >
                      <Image
                        style={styles.img}
                        source={Iconpack.PIN_CANCEL}
                      />
                    </TouchableOpacity>
                  ) : num.id == 11 ? (
                    <TouchableOpacity
                      key={num.id.toString()}
                      onPress={() => {
                        confirmPin();
                      }}
                      style={
                        AppStore.isiOS ? styles.number : styles.number2
                      }
                    >
                      <Image
                        style={styles.img}
                        source={Iconpack.PIN_CHECK}
                      />
                    </TouchableOpacity>
                  ) : (
                    <TouchableOpacity
                      key={num.id.toString()}
                      onPress={() => onPressNumber(num.id.toString())}
                      style={
                        AppStore.isiOS ? styles.number : styles.number2
                      }
                    >
                      <Text style={styles.numberText}>
                        {num.id.toString()}
                      </Text>
                    </TouchableOpacity>
                  )}
                </>
              );
            })}
          </View>
        </View>
        {/* </Screen> */}
      </>
    )}
    </Observer>
  );
 }

  export default PinAuthentication;

  const styles = StyleSheet.create({
    mod0: { alignItems: "center", justifyContent: "center" },
     container: {
      flex: 1,
      position: "absolute",
      top: 0,
      right: 0,
      left: 0,
      bottom: 0,
      backgroundColor: "#021831",
    },
   pinConfirmationText: {
   textAlign: "center",
   marginTop: hRem * 44,
   color: "white",
   ...Theme.encodeSansMed3,
   lineHeight: hRem * 19.07,
},
 borderStyleBase: {
   width: 30,
   height: 45,
 },
 borderStyleHighLighted: {
   borderColor: "#707070",
 },
 underlineStyleBase: {
   width: wRem * 62,
   height: 45,
   borderWidth: 0,
   borderBottomWidth: 1,
 },
 underlineStyleHighLighted: {
   borderColor: "#FFFFFF",
 },
 number: {
  borderRadius:
  Math.round(
    Dimensions.get("window").width + Dimensions.get("window").height
     ) / 2,
   width: Dimensions.get("window").width * 0.2,
   height: Dimensions.get("window").width * 0.2,
   backgroundColor: "#000000",
   justifyContent: "center",
   alignItems: "center",
   marginHorizontal: wRem * 12,
   marginVertical: hRem * 9,
 },
 number2: {
   borderRadius:
     Math.round(
       Dimensions.get("window").width + Dimensions.get("window").height
     ) / 2,
   width: Dimensions.get("window").width * 0.2,
   height: Dimensions.get("window").width * 0.2,
   backgroundColor: "#000000",
   justifyContent: "center",
   alignItems: "center",
   marginHorizontal: wRem * 12,
   marginVertical: hRem * 9,
   shadowColor: "rgba(27, 100, 206, 0.8)",
   shadowOffset: {
     width: 1,
     height: 5,
   },
   shadowOpacity: 1.5,
   shadowRadius: 5,
   elevation: 10,
 },
 numberContainer: {
   flexDirection: "row",
   flexWrap: "wrap",
   marginTop: hRem * 99,
   alignItems: "center",
   justifyContent: "center",
   shadowColor: Theme.shadow_Button,
   shadowOffset: {
     width: 1,
     height: 1,
   },
   shadowOpacity: 1.5,
   shadowRadius: 5,

   elevation: 3,
 },

 numberText: {
...Theme.encodeSansMed4,
// lineHeight: hRem * 16,
// position: "absolute",
textAlign: "center",
   color: Theme.white_color,
  },
  codeContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginHorizontal: wRem * 49,
    marginTop: hRem * 50,
  },
  inputBox: {
    width: wRem * 62,
    borderBottomWidth: 1,
    borderColor: "#707070",
    alignItems: "center",
    justifyContent: "space-between",
   },
    inputBox1: {
    width: wRem * 62,
    borderBottomWidth: 1,
    borderColor: "#FFFFFF",
    alignItems: "center",
    justifyContent: "space-between",
  },
 inputText: {
    color: "white",
    ...Theme.encodeSansMed3,
    marginBottom: hRem * 21,
  },
  img: {
    width: wRem * 30,
    height: hRem * 22,
  },
});

【讨论】:

  • 不要创建单个状态对象。这是一种反模式,会在您的组件中产生副作用。最好将您的状态对象拆分为单独的 useState 变量
  • @SolomonYunana 你能用单独的 useState 进行编辑吗?因为我无法用这个状态对象存储 pin,谢谢
  • @sourabh atigre 我已经分离了所有 useState 对象
  • 非常感谢你的辛勤工作,现在我可以做任何类组件来实现功能
【解决方案2】:

为了将类组件转换为功能组件,您需要分离类和道具行为,而是使用“钩子”。

我会给你一些例子,而不是手动改变你的整个解决方案;

PinAuthentication = (props) => {

const [passcode, setPasscode] = useState('')

const showToast = () => Toast.show('Please enter a valid pin', Toast.LONG)

return (
    <Observer>
    {() => (
        <>
            <FastImage ... />
            ...
        </>
    )}
  )
}


因此,如果您想继续使用状态,请使用 UseState。使用“function”或“const”完全声明您的方法。并删除this 的所有实例,只需使用作用域变量名即可。

【讨论】:

    【解决方案3】:

    看看功能组件documentation

    • 无论您在何处使用 this.state,都希望将其转换为 React.useState
    • 您不需要渲染,因为您只需要返回一个 renderable 对象 (jsx/null/React.Fragment)。
    • 您的函数几乎已经存在,只需添加 const 并在没有 this 前缀的情况下引用它们。

    那么你将完成 90% 的路程。

    【讨论】:

      【解决方案4】:
      import React, { Component, useState } from "react";
      import {
        StyleSheet,
        Text,
        View,
        Image,
        TouchableOpacity,
        Dimensions,
      } from "react-native";
      import AppStore from "../../stores/AppStore";
      import Theme from "../../utils/Theme";
      import { Observer } from "mobx-react";
      import Iconpack from "../../utils/Iconpack";
      import FastImage from "react-native-fast-image";
      import { Screen } from "../CommonComponent/Screen";
      import PinAuthenticationStore from "../../stores/PinAuthenticationStore";
      import Toast from "react-native-simple-toast";
      import Header from "../CommonComponent/Header";
      
      const hRem = AppStore.screenHeight / 812;
      const wRem = AppStore.screenWidth / 375;
      
      function PinAuthentication(props) {
        const [state, setState] = useState({
          passcode: ["", "", "", ""],
          pin: "",
          confirmThePin: false,
          reconfirmPin: "",
        });
      
        const showToast = () => {
          // ToastAndroid.show("Pick Enter Valid Pin !", ToastAndroid.SHORT);
          Toast.show("Please Enter Valid Pin !", Toast.LONG);
        };
      
        const onPressNumber = (num) => {
          let tempCode = state.passcode;
          for (var i = 0; i < tempCode.length; i++) {
            if (tempCode[i] == "") {
              tempCode[i] = num;
              if (state.confirmThePin) {
                setState({ ...state, reconfirmPin: state.reconfirmPin + num });
              } else {
                setState({ ...state, pin: state.pin + num });
              }
              break;
            } else {
              continue;
            }
          }
          setState({ ...state, passcode: tempCode });
        };
      
        const onPressCancel = () => {
          let tempCode = state.passcode;
          for (var i = tempCode.length - 1; i >= 0; i--) {
            if (tempCode[i] != "") {
              tempCode[i] = "";
              setState({
                ...state,
                pin: state.pin.slice(0, i),
                reconfirmPin: state.reconfirmPin.slice(0, i),
              });
              break;
            } else {
              continue;
            }
          }
          // if(tempCode.length==0){
          console.log("cancel", tempCode);
          // }
          setState({ ...state, passcode: tempCode });
        };
      
        const reset = () => {
          setState({
            passcode: ["", "", "", ""],
            confirmThePin: false,
            reconfirmPin: "",
            pin: "",
          });
        };
      
        const confirmPin = () => {
          if (AppStore.idExist) {
            if (state.pin == AppStore.userPin) {
              props.navigation.navigate("MainAdd");
              reset();
              // AppStore.setFields("isNewUserPin", true);
            } else {
              showToast();
              setState({ ...state, passcode: ["", "", "", ""], pin: "" });
              // AppStore.setFields("isNewUserPin", false);
            }
          } else if (state.pin == state.reconfirmPin) {
            // console.log("new user");
            PinAuthenticationStore.setPinForNewUser(state.reconfirmPin);
            // PinAuthenticationStore.setUserPin(this.state.reconfirmPin)
            PinAuthenticationStore.setStringIsLoggedIn("true");
            reset();
            props.navigation.navigate("MainAdd");
            // AppStore.setFields("isNewUserPin", true);
          } else if (
            state.pin != state.reconfirmPin &&
            state.reconfirmPin.length > 0
          ) {
            setState({
              passcode: ["", "", "", ""],
              confirmThePin: false,
              reconfirmPin: "",
              pin: "",
            });
            showToast();
            // AppStore.setFields("isNewUserPin", false);
          } else {
            if (state.pin.length == 4 && !state.confirmThePin) {
              setState({ ...state, passcode: ["", "", "", ""], confirmThePin: true });
            } else if (state.reconfirmPin.length == 4) {
              setState({ ...state, passcode: ["", "", "", ""] });
            }
            // AppStore.setFields("isNewUserPin", false);
          }
      
          console.log("confirm pin", state.pin, AppStore.userPin);
        };
      
        let numbers = [
          { id: 1 },
          { id: 2 },
          { id: 3 },
          { id: 4 },
          { id: 5 },
          { id: 6 },
          { id: 7 },
          { id: 8 },
          { id: 9 },
          {
            id: 10,
          },
          { id: 0 },
          {
            id: 11,
          },
        ];
      
        return (
          <Observer>
            {() => (
              <>
                {/* <Screen
                    style={{ flex: 1 }}
                    statusBar={"light-content"}
                    variant={true}
                    showMenu={false}
                    onNavigate={this.props.navigation}
                  > */}
                <FastImage
                  style={styles.container}
                  source={Iconpack.PIN_SCREEN_BG}
                  resizeMode={FastImage.resizeMode.cover}
                />
                <Header
                  headerText="Set new PIN"
                  onPress={() => {
                    this.props.navigation.navigate("WalkThrough");
                  }}
                />
                <View>
                  <Text style={styles.pinConfirmationText}>
                    {AppStore.idExist
                      ? `Enter current PIN`
                      : this.state.confirmThePin
                      ? `Re-confirm PIN`
                      : `Enter new PIN`}
                  </Text>
                </View>
                <View style={styles.codeContainer}>
                  {this.state.passcode.map((p, i) => {
                    console.log("xxxx", p);
                    let style = p != "" ? styles.inputBox1 : styles.inputBox;
                    let passMask = p != "" ? "*" : "";
                    return (
                      <View style={style} key={i}>
                        <Text style={styles.inputText}>{passMask}</Text>
                      </View>
                    );
                  })}
                </View>
      
                <View style={styles.mod0}>
                  <View style={styles.numberContainer}>
                    {numbers.map((num, numb) => {
                      return (
                        <>
                          {num.id == 10 ? (
                            <TouchableOpacity
                              key={num.id.toString()}
                              onPress={() => this.onPressCancel()}
                              style={AppStore.isiOS ? styles.number : styles.number2}
                            >
                              <Image
                                style={styles.img}
                                source={Iconpack.PIN_CANCEL}
                              />
                            </TouchableOpacity>
                          ) : num.id == 11 ? (
                            <TouchableOpacity
                              key={num.id.toString()}
                              onPress={() => {
                                this.confirmPin();
                              }}
                              style={AppStore.isiOS ? styles.number : styles.number2}
                            >
                              <Image style={styles.img} source={Iconpack.PIN_CHECK} />
                            </TouchableOpacity>
                          ) : (
                            <TouchableOpacity
                              key={num.id.toString()}
                              onPress={() => this.onPressNumber(num.id.toString())}
                              style={AppStore.isiOS ? styles.number : styles.number2}
                            >
                              <Text style={styles.numberText}>
                                {num.id.toString()}
                              </Text>
                            </TouchableOpacity>
                          )}
                        </>
                      );
                    })}
                  </View>
                </View>
                {/* </Screen> */}
              </>
            )}
          </Observer>
        );
      }
      
      export default PinAuthentication;
      
      const styles = StyleSheet.create({
        mod0: { alignItems: "center", justifyContent: "center" },
        container: {
          flex: 1,
          position: "absolute",
          top: 0,
          right: 0,
          left: 0,
          bottom: 0,
          backgroundColor: "#021831",
        },
        pinConfirmationText: {
          textAlign: "center",
          marginTop: hRem * 44,
          color: "white",
          ...Theme.encodeSansMed3,
          lineHeight: hRem * 19.07,
        },
        borderStyleBase: {
          width: 30,
          height: 45,
        },
      
        borderStyleHighLighted: {
          borderColor: "#707070",
        },
      
        underlineStyleBase: {
          width: wRem * 62,
          height: 45,
          borderWidth: 0,
          borderBottomWidth: 1,
        },
      
        underlineStyleHighLighted: {
          borderColor: "#FFFFFF",
        },
        number: {
          borderRadius:
            Math.round(
              Dimensions.get("window").width + Dimensions.get("window").height
            ) / 2,
          width: Dimensions.get("window").width * 0.2,
          height: Dimensions.get("window").width * 0.2,
          backgroundColor: "#000000",
          justifyContent: "center",
          alignItems: "center",
          marginHorizontal: wRem * 12,
          marginVertical: hRem * 9,
        },
        number2: {
          borderRadius:
            Math.round(
              Dimensions.get("window").width + Dimensions.get("window").height
            ) / 2,
          width: Dimensions.get("window").width * 0.2,
          height: Dimensions.get("window").width * 0.2,
          backgroundColor: "#000000",
          justifyContent: "center",
          alignItems: "center",
          marginHorizontal: wRem * 12,
          marginVertical: hRem * 9,
          shadowColor: "rgba(27, 100, 206, 0.8)",
          shadowOffset: {
            width: 1,
            height: 5,
          },
          shadowOpacity: 1.5,
          shadowRadius: 5,
      
          elevation: 10,
        },
        numberContainer: {
          flexDirection: "row",
          flexWrap: "wrap",
          marginTop: hRem * 99,
          alignItems: "center",
          justifyContent: "center",
          shadowColor: Theme.shadow_Button,
          shadowOffset: {
            width: 1,
            height: 1,
          },
          shadowOpacity: 1.5,
          shadowRadius: 5,
      
          elevation: 3,
        },
      
        numberText: {
          ...Theme.encodeSansMed4,
          // lineHeight: hRem * 16,
          // position: "absolute",
          textAlign: "center",
          color: Theme.white_color,
        },
        codeContainer: {
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "space-between",
          marginHorizontal: wRem * 49,
          marginTop: hRem * 50,
        },
        inputBox: {
          width: wRem * 62,
          borderBottomWidth: 1,
          borderColor: "#707070",
          alignItems: "center",
          justifyContent: "space-between",
        },
        inputBox1: {
          width: wRem * 62,
          borderBottomWidth: 1,
          borderColor: "#FFFFFF",
          alignItems: "center",
          justifyContent: "space-between",
        },
        inputText: {
          color: "white",
          ...Theme.encodeSansMed3,
          marginBottom: hRem * 21,
        },
        img: {
          width: wRem * 30,
          height: hRem * 22,
        },
      });
      
      
      
      

      【讨论】:

      • 你能不能用单独的 useState 编辑因为我不能用这个状态对象存储 pin 谢谢@BYIRINGIROEmmanuel
      • 单独的 setState 将导致更多的代码,这在可读性和维护方面增加了更多的权重。这个想法是获取现有状态值的副本,然后将pin 更改为新值。 setState({...state,pin:[NEW_PIN_VALUE]})
      猜你喜欢
      • 2021-09-16
      • 2022-01-08
      • 1970-01-01
      • 2020-06-04
      • 2021-03-06
      • 2020-02-08
      • 2022-01-11
      相关资源
      最近更新 更多