javascript React Native Biolerplate

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript React Native Biolerplate相关的知识,希望对你有一定的参考价值。

'use strict'

import React, {Component} from 'react';
import { View, StatusBar, ActivityIndicator, Image } from 'react-native';
import { Content, Button, Text, Form, Item, Input, Label, StyleProvider } from 'native-base';
import { LoadingModal, FormErrorMessage, Container, Toast } from '@components';
import { loading } from '@actions/AppAction';
import { connect } from 'react-redux';
import Reactotron from 'reactotron-react-native';
import { Auth, Location, Connection } from '@services';
import { PermissionsHelper, StringHelper } from '@helpers';
import { fetchUser } from '@actions/UserAction';
import validator from 'validator';
import { Styles, Paths } from '@config';
import SplashScreen from 'react-native-splash-screen';

const errorMessages = {
    emptyEmail: 'Email tidak boleh kosong',
    emptyPassword: 'Password tidak boleh kosong',
    emailFormat: 'Format email salah',
};

class ExampleScreen extends Component {
    constructor(props) {
        super(props);

        this.state = {
            email: __DEV__ ? 'admin@mailinator.com' : null,
            emailInputError: false,
            emailErrorMessage: '',

            password: __DEV__ ? '123456' : null,
            passwordInputError: false,
            passwordErrorMessage: '',

            securePassword: true
        }

        this.inputs = {};
    }

    static navigationOptions = ({ navigation }) => {
        const { params } = navigation.state;
        
        return {
            title: 'Home',
            // header: null
        }
    }

    _validation = (field, text) => {
        if ( field === 'email' )
        {
            this.setState({ email: StringHelper.cleanSpace(text) });

            // if (validator.isEmpty(text)) 
            //     this.setState({ emailErrorMessage: errorMessages.emptyEmail, emailInputError: true });
            // else if (!validator.isEmail(text))
            //     this.setState({ emailErrorMessage: errorMessages.emailFormat, emailInputError: true });
            // else
            //     this.setState({ emailErrorMessage: '', emailInputError: false });
        }

        else if ( field === 'password' )
        {
            this.setState({ password: text });

            // if (validator.isEmpty(text)) 
            //     this.setState({ passwordErrorMessage: errorMessages.emptyPassword, passwordInputError: true });
            // else
            //     this.setState({ passwordErrorMessage: '', passwordInputError: false });
        }


    }

    _validationSubmit = () => {
        let validated = false;
        let emailValidate = validator.isEmpty(this.state.email);
        let passwordValidate = validator.isEmpty(this.state.password);
        let emailFormatValidate = validator.isEmail(this.state.email);

        if ( !emailValidate && !passwordValidate && emailFormatValidate )
        {
            validated = true;
        } 
        else 
        {
            if (emailValidate) 
            {
                this.setState({ emailErrorMessage: errorMessages.emptyEmail, emailInputError: true });
            }
            else
            {
                if ( !emailFormatValidate )
                    this.setState({ emailErrorMessage: errorMessages.emailFormat, emailInputError: true });
            }

            if (passwordValidate) 
            {
                this.setState({ passwordErrorMessage: errorMessages.emptyPassword, passwordInputError: true });
            }
        }

        return validated;
    }

    _register = () => {

        return this.props.navigation.navigate('Register');

    }

    _login = async () => {

        if ( this._validationSubmit() )
        {    
            if ( await Connection.check(true) )
            {
                this.props.loading();

                let credentials = {
                    email: this.state.email.trim(),
                    password: this.state.password,
                    accessTokenName: 'android-com.asliri.amano'
                };

                Promise.all([

                    await Auth.attempt(credentials)

                ]).then(async ([login]) => {

                    this.props.loading(false);

                    if ( login === true )
                    {
                        return this.props.navigation.navigate('AppStack');
                    }
                
                    Toast.show(login);  

                }).catch((e) => {

                    Reactotron.log(e);

                    this.props.loading(false);

                    Toast.show('Terjadi kesalahan dengan aplikasi');  

                }); 
            }
        }
        else
        {
            Toast.show('Terdapat kesalahan dalam pengisian formulir.');  
        }

    }

    _focusNextField(nextField) {
        this.inputs[nextField]._root.focus();
    }

    async componentDidMount()
    {
        setTimeout(async () => { 
            SplashScreen.hide(); 

            await PermissionsHelper.location();
            await PermissionsHelper.camera();
            // await PermissionsHelper.readPhoneState();
            await PermissionsHelper.readSms();
            await PermissionsHelper.sendSms();
            // await PermissionsHelper.recordAudio();

            await Location.find();
            await Connection.deviceRegister();
        }, 750);
        
        // this.inputs['email']._root.focus();

        
    }
    
    render() {

        return (
            <Container loading={this.props.app.loading}>
                <StatusBar
                    backgroundColor="white"
                    barStyle="dark-content"
                />

                <Content showsVerticalScrollIndicator={false} padder>
                    <View>
                        <View style={{ alignItems: 'center', paddingVertical: 30 }}>
                            <Image source={Paths.logoLogin} resizeMode={"contain"} style={{ width: 150, height: 150 }} fadeDuration={0} />
                        </View>

                        <Form style={{ marginBottom: 30, padding: 0 }}>
                            <Item style={Styles.formItem} error={this.state.emailInputError} stackedLabel>
                                <Label>E-Mail</Label>
                                <Input 
                                    style={Styles.formInput}
                                    maxLength={200}
                                    returnKeyType={"next"}
                                    keyboardType={"email-address"}
                                    blurOnSubmit={false}
                                    onBlur={() => this._validation('email', this.state.email)}
                                    onChangeText={(text) => this._validation('email', text)}
                                    ref={input => {
                                        this.inputs['email'] = input;
                                    }}
                                    disabled={this.props.app.loading}
                                    autoCapitalize={"none"}
                                    onSubmitEditing={(text) => this._focusNextField('password')}
                                    value={this.state.email} />
                            </Item>

                            {
                                this.state.emailInputError ?
                                    <FormErrorMessage message={this.state.emailErrorMessage} />
                                :
                                    null
                            }

                            <Item style={[Styles.formItem, { marginTop: 30 }]} error={this.state.passwordInputError} stackedLabel>
                                <Label>Kata Sandi</Label>
                                <Input 
                                style={Styles.formInput}
                                maxLength={200}
                                secureTextEntry={true}
                                onBlur={() => this._validation('password', this.state.password)}
                                onChangeText={(text) => this._validation('password', text)}
                                ref={input => {
                                    this.inputs['password'] = input;
                                }}
                                disabled={this.props.app.loading}
                                autoCapitalize={"none"}
                                value={this.state.password} />
                            </Item>

                            {
                                this.state.passwordInputError ?
                                    <FormErrorMessage message={this.state.passwordErrorMessage} />
                                :
                                    null
                            }
                        </Form>

                    </View>

                </Content>

                <View style={{ padding: 10 }}>
                    <Button style={{ marginBottom: 10 }} disabled={this.props.app.loading} onPress={this._login} block>
                        { this.props.app.loading ? <ActivityIndicator /> : <Text>Masuk</Text> }
                    </Button>
                    
                    <Button disabled={this.props.app.loading} onPress={this._register} bordered block>
                        <Text>Daftar</Text>
                    </Button>
                </View>
            </Container>
        );
    }
}

const mapReduxStateToComponentProps = state => ({
    app: state.app
});

export default connect(mapReduxStateToComponentProps, { loading, fetchUser })(ExampleScreen);

以上是关于javascript React Native Biolerplate的主要内容,如果未能解决你的问题,请参考以下文章

React-native:从 javascript 迁移到 typescript

javascript React Native有用的命令

javascript React Native Biolerplate

javascript React Native Handy

javascript React Native打字稿配置

javascript [ss]你好#react native