如何在React Native中编写格式正确的代码?

时间:2019-12-31 06:02:17

标签: react-native code-formatting

我是React Native的新手。我想编写格式正确的代码,以便可以轻松管理大型应用程序,并可以通过新更改来更改现有代码。

现在我将所有组件都放在一个块中,所以当我要更改它时我很困惑。

我进行了如下所示的注册屏幕。我的代码搞砸了,看起来很扭曲。请帮助我如何将代码管理成良好的片段方式。

import LoginScreen from './Login';
import React, {Component} from 'react';
import 'react-native-gesture-handler';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';

import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  TextInput,
  Button,
  Image,
  KeyboardAvoidingView,
} from 'react-native';

class RegistrationScreen extends Component {
  state = {
    textInputTexts: {
      username: '',
      password: '',
      email: '',
      phoneno: '',
    },
    validFlags: {
      username: false,
      password: false,
      email: false,
      phoneno: false,
    },
  };

  validateEmail = text => {
    console.log(text);
    let reg = /^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i;
    console.log(reg.test(text));

    if (reg.test(text) === false) {
      console.log('Email is Not Correct');
      return false;
    } else {
      console.log('Email is Correct');
      return true;
    }
  };

  validatePassword = text => {
    console.log(text);
    var passRegex = new RegExp(
      '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})',
    );

    console.log(passRegex.test(text));

    if (passRegex.test(text) === false) {
      console.log('Password is Not Valid');
      return false;
    } else {
      console.log('Password is Correct');
      return true;
    }
  };

  validateUsername = text => {
    console.log(text);
    var usernameRegex = new RegExp('(?=.*[a-fA-F])(?=.{5,})');

    console.log(usernameRegex.test(text));

    if (usernameRegex.test(text) === false) {
      console.log('Username is Not Valid');
      return false;
    } else {
      console.log('Username is Correct');
      return true;
    }
  };

  textInputTextChanged = (key, value) => {
    var valid = false;
    if (key === 'username') {
      valid = this.validateUsername(value);
    } else if (key === 'password') {
      valid = this.validatePassword(value);
    } else if (key === 'email') {
      valid = this.validateEmail(value);
    } else if (key === 'phoneno') {
      if (value.length === 10) {
        valid = true;
      }
    }
    if (valid) {
      console.log('Input is valid');
    } else {
      console.log('Input is not valid');
    }
    //this.setState(Object.assign(this.state.textInputTexts, {[key]: value}));
    this.setState({
      textInputTexts: {...this.state.textInputTexts, [key]: value},
      validFlags: {...this.state.validFlags, [key]: valid},
    });
    //console.log(this.state);
  };

  signUp = () => {
    const {validFlags} = this.state;
    console.log('Sign up click');

    if (
      validFlags.username &&
      validFlags.password &&
      validFlags.email &&
      validFlags.phoneno
    ) {
      // navigate to Login screen
      console.log('Go to login screen');

      this.props.navigation.navigate('LoginScreen');
    }
  };
  render() {
    const {validFlags} = this.state; // this is for constant parameter of this.state to avoid writing this.state.validFlags
    console.log(this.state);
    const errorImage = (
      <Image
        source={require('./../images/error-icon.png')}
        style={styles.errorImageStyle}
      />
    );
    return (
      <SafeAreaView>
        <ScrollView>
          <View>
            <View style={styles.textInputContainer}>
              <TextInput
                style={styles.textInput}
                placeholder="Username"
                autoCapitalize="none"
                placeholderTextColor="#a7a7a7"
                onChangeText={value =>
                  this.textInputTextChanged('username', value)
                }
              />
              {!validFlags.username && errorImage}
            </View>
            {!validFlags.username && (
              <Text style={styles.errorLabelStyle}>
                Username must contain 5 alphabets
              </Text>
            )}
            <View style={styles.textInputContainer}>
              <TextInput
                style={styles.textInput}
                placeholder="Password"
                autoCapitalize="none"
                placeholderTextColor="#a7a7a7"
                secureTextEntry={true}
                onChangeText={value =>
                  this.textInputTextChanged('password', value)
                }
              />
              {!validFlags.password && errorImage}
            </View>
            {!validFlags.password && (
              <Text style={styles.errorLabelStyle}>
                Password must contain 8 characters with atleast one special
                character, Capital and small characters and numbers
              </Text>
            )}
            <View style={styles.textInputContainer}>
              <TextInput
                style={styles.textInput}
                placeholder="Email Id"
                autoCapitalize="none"
                placeholderTextColor="#a7a7a7"
                onChangeText={value =>
                  this.textInputTextChanged('email', value)
                }
              />
              {!validFlags.email && errorImage}
            </View>
            {!validFlags.email && (
              <Text style={styles.errorLabelStyle}>
                Email text should be valid email id
              </Text>
            )}
            <View style={styles.textInputContainer}>
              <TextInput
                style={styles.textInput}
                placeholder="Phone No."
                autoCapitalize="none"
                placeholderTextColor="#a7a7a7"
                keyboardType="number-pad"
                onChangeText={value =>
                  this.textInputTextChanged('phoneno', value)
                }
              />
              {!validFlags.phoneno && errorImage}
            </View>
            {!validFlags.phoneno && (
              <Text style={styles.errorLabelStyle}>
                Phone number must contain 10 digits
              </Text>
            )}
            <Button title="Sign Up" onPress={this.signUp} />
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    alignSelf: 'center',
    width: 300,
    paddingTop: 300,
  },
  textInput: {
    flex: 1,
    height: 50,
    backgroundColor: '#E2E2E2',
    marginTop: 10,
    marginRight: 10,
    padding: 8,
    color: 'black',
    borderRadius: 10,
    fontSize: 16,
    fontWeight: '500',
  },
  textInputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  errorImageStyle: {
    width: 20,
    height: 20,
  },
  errorLabelStyle: {
    alignSelf: 'flex-start',
    color: 'red',
    paddingLeft: 8,
    marginBottom: 10,
    fontSize: 12,
  },
});

const AppNavigator = createStackNavigator(
  {
    RegistrationScreen: {
      screen: RegistrationScreen,
    },
    LoginScreen: {
      screen: LoginScreen,
    },
  },
  {
    initialRouteName: 'LoginScreen',
    defaultNavigationOptions: {
      title: 'App',
    },
  },
);

export default createAppContainer(AppNavigator);

1 个答案:

答案 0 :(得分:1)

使用本机反应的最大优点是它的组件驱动。您可以遵循下面提到的一些内容,

  • 有单独的文件用于导航,我在注册页面上看到createStackNavigator和其他内容,它不好,必须将其放在其他文件中。
  • 在不同文件中分离出样式,每个组件也必须从其引用的位置开始具有相应的样式文件。
  • 编写尽可能多的可重用组件,例如在您的情况下,

    <View style={styles.textInputContainer}>
      <TextInput
         style={styles.textInput}
         placeholder="Email Id"
         autoCapitalize="none"
         placeholderTextColor="#a7a7a7"
         onChangeText={value =>
            this.textInputTextChanged('email', value)
         }
       />
       {!validFlags.email && errorImage}
    </View>
    

重复很多次,将其作为一个单独的组件并仅将所需的道具传递给它,让普通事物保持原样。

  • 从整个应用程序体系结构的角度来看,请使用redux
  • 使用Prettier进行代码格式化。