簡體   English   中英

顯示特定的錯誤消息 - NativeBase/React Native

[英]Show specific error message - NativeBase/React Native

目前正在學習 react-native,構建一個注冊表單(使用 NativeBase 組件)並希望為每個輸入字段添加驗證。

我目前面臨的問題是我沒有看到具體的錯誤消息,總是回退到默認值

#SignUp.js
export const SignUp = ({navigation}) => {
  const [errors, setErrors] = useState({});

  const validateFirstName = () => {
    if (formData.firstName === undefined) {
    setErrors({
      ...errors,
      name: 'First Name is required',
    });
    return false;
    } else if (formData.firstName.length < 3) {
      setErrors({
        ...errors,
        name: 'First Name is too short',
      });
      return false;
    }
    return true;
  };

  // First Name Input Field
  <FormControl isRequired isInvalid={'name' in errors}>
  <FormControl.Label>First Name</FormControl.Label>
  <Input value={firstName} onChangeText={firstName => setFirstName(firstName)}/>
  {'name' in errors ?
    <FormControl.ErrorMessage>Please enter a valid first name</FormControl.ErrorMessage>: ''
  }
  </FormControl>
}

因此,在此示例中,假設我提交了一個空的名字,我希望看到錯誤消息First Name is required ,但我得到Please enter a valid first name

我似乎沒有正確訪問錯誤消息,我錯過了什么嗎?

謝謝

你錯過了一件小事。 只需更換

<FormControl.ErrorMessage>Please enter a valid first name</FormControl.ErrorMessage>: ''

<FormControl.ErrorMessage>{errors.name}</FormControl.ErrorMessage>: ''

因此,當組件位於invalid的 state 中時,組件FormControl.ErrorMessage將顯示其子級。 你可以在這里閱讀更多關於它的信息

我創建了一個小吃,展示如何有效地使用 FormControl。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM