Методология проверки формы React Native - PullRequest
0 голосов
/ 09 июля 2020

Я новичок в React Native. Я пытаюсь создать полнофункциональный экран входа в систему, используя некоторые методы проверки пользовательской формы. Теперь у меня есть запасы проверки формы из-за того, что метод setState в реакции является асинхронным. Увидев мой приведенный ниже код, может ли кто-нибудь порекомендовать мне, что лучше всего.

Я хочу, чтобы пользовательский путь был описан ниже

Пользователь вводит свой адрес электронной почты и пароль, и при нажатии на кнопке SignUp я проверю ввод и, если есть ошибка, я установлю состояние моей ошибки и покажу сообщение об ошибке. Если мое состояние равно пустой строке, это будет означать, что ошибки проверки нет, и я могу продолжить свою операцию. Ниже приведен полный код экрана регистрации

import React, {useState, useEffect} from 'react';
import {
  Container,
  Content,
  H1,
  Form,
  Item,
  Label,
  Input,
  Button,
  Text,
  Icon,
} from 'native-base';
import {globalStyles} from '../../helper/globalStyles';
import {
  vaidateEmailAddress,
  validatePassword,
} from '../../helper/validationfunctions';

const RegisterScreen = ({navigation}) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const [emailInputError, setEmailInputError] = useState(null);
  const [emailInputErrorMessage, setEmailInputErrorMessage] = useState('');

  const [passwordInputError, setPasswordInputError] = useState(null);
  const [passwordInputErrorMessage, setPasswordInputErrorMessage] = useState(
    '',
  );

  return (
    <Container style={globalStyles.container}>
      <Content contentContainerStyle={globalStyles.content}>
        <H1>Register</H1>
        <H1 />
        <Form>
          <Item error={emailInputError} style={globalStyles.item}>
            <Label>Email</Label>
            <Input
              onChangeText={text => {
                setEmail(text);
              }}
            />
          </Item>
          {emailInputError && (
            <Item style={globalStyles.erroritem}>
              <Icon name="ios-close-circle" style={{color: 'red'}} />
              <Text style={globalStyles.erroritemText}>
                {emailInputErrorMessage}
              </Text>
            </Item>
          )}
          <Item error={passwordInputError} style={globalStyles.item}>
            <Label style={globalStyles.labelText}>Password</Label>
            <Input
              style={globalStyles.input}
              onChangeText={text => {
                setPassword(text);
              }}
            />
          </Item>

          {passwordInputError && (
            <Item style={globalStyles.erroritem}>
              <Icon name="ios-close-circle" style={{color: 'red'}} />
              <Text style={globalStyles.erroritemText}>
                {passwordInputErrorMessage}
              </Text>
            </Item>
          )}

          <Item style={(globalStyles.item, globalStyles.lastItem)} last>
            <Button
              onPress={() => {
                //First Validate Empty Field
                if (
                  email === '' ||
                  email === null ||
                  !vaidateEmailAddress(email)
                ) {
                  setEmailInputError('error');
                  console.log('Value changed' + emailInputError);
                  setEmailInputErrorMessage(
                    'The email you provided is not a valid email address',
                  );

                  console.log(email === '');
                  console.log(email === null);
                  console.log(vaidateEmailAddress(email));
                }
                if (
                  password === '' ||
                  password === null ||
                  !validatePassword(password)
                ) {
                  setPasswordInputError('error');
                  setPasswordInputErrorMessage(
                    'The password you provided is not a valid password',
                  );
                }
                setTimeout(() => {
                  if (emailInputError === null && passwordInputError === null) {
                    console.log(
                      'Email: ' +
                        emailInputError +
                        ' Password: ' +
                        passwordInputError +
                        ' I am fired',
                    );
                    // TODO: Add firebase code
                  }
                }, 100);

                navigation.navigate('RegisterScreen');
              }}>
              <Text>Signup</Text>
            </Button>
          </Item>

          <Item style={(globalStyles.item, globalStyles.lastItem)} last>
            <Button
              bordered
              onPress={() => {
                navigation.pop();
              }}>
              <Text>Go Back</Text>
            </Button>
          </Item>
        </Form>
      </Content>
    </Container>
  );
};

export default RegisterScreen;

1 Ответ

0 голосов
/ 10 июля 2020

Написание и проверка форм могут быть проблемой :( Я рекомендую использовать стороннюю библиотеку, чтобы облегчить вашу жизнь. Одна из лучших библиотек для React Native - Formik. Вы можете найти документацию по интеграции React Native здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...