React-Native 二、登录注册模块开发

作者: 直男程序员 | 来源:发表于2018-08-16 14:46 被阅读34次
    react-native

    前段时间公司项目比较赶, 没时间写文章, 这两天闲下来了, 总结了一下, 写了一篇比较综合的UI项目, 登录注册模块, 包含UI 网络请求等功能, 希望对大家理解React Native的界面布局和网络请求有一定的帮助.

    项目可到github下载: https://github.com/YTiOSer/YTReact-Native_LoginUI

    1.头文件

    这个项目中用到了多个UI控件和导航, 所以需要引入多个控件和React Navigation,导航的使用方法上篇文章已经讲述, 这里就不再讲了,代码如下所示:

    import React, { Component } from 'react';
    import { createStackNavigator } from 'react-navigation';
    import ButtonView from './ButtonView';
    import RegistView from './regist/RegistView';
    
    import {
      Platform,
      StyleSheet,
      Text,
      View, 
      TextInput, 
      Button,
      Alert,
      Fetch,
      Dimensions,
    } from 'react-native';
    

    2. 封装控件

    项目中针对按钮ButtonView进行了封装, 页面中使用的按钮都可以使用封装的控件, 这样方便管理和使用, 代码在ButtonView.js目录下, 具体封装代码如下:

    export default class ButtonView extends React.Component {
    
        static defaultProps = {
            btnName: 'Button',
            underlayColor: 'gray',
        };
    
        constructor(props) {
            super(props);
        }
    
      render() {
        return (
            <View style = {styles.container}>
                <TouchableHighlight
                    style={[styles.btnDefaultStyle,this.props.btnStyle,styles.center]}
                    activeOpacity={0.5}
                    underlayColor={this.props.underlayColor}
                    onPress={this.props.onPress}>
    
                    <Text style={[styles.textDefaultStyle, this.props.textStyle]}>{this.props.btnName}</Text>
    
                </TouchableHighlight>
            </View>
    
            );
      }
    }
    
    

    3. 宏定义字段

    项目开发中经常会使用到当前设备的屏幕宽高, 或者自定义常使用的字段, 这时候统一定义成宏方便使用.

    const {width, height} = Dimensions.get('window');
    const SCREEN_WIDTH = width;
    
    const PWRightWid = 100;
    

    4. 定义绑定事件

    在登录注册页面中, 我们经常需要获取到登录的用户名,密码,验证码,手机号等字段, 这时候在React Native中就需要定义对应的字段绑定后来获取.

        this._getUserName = this._getUserName.bind(this); //获取用户名
        this._getUserPW = this._getUserPW.bind(this); //获取密码
        this._onClickLogin = this._onClickLogin.bind(this); //登录
        this._getPhoneCode = this._getPhoneCode.bind(this); //获取验证码
        this._onClickSIM = this._onClickSIM.bind(this); //点击切换账号手机号登录
        this._onClickForgetPW = this._onClickForgetPW.bind(this); //点击忘记密码
        this._hiddenGetCodeBtn = this._hiddenGetCodeBtn.bind(this); //隐藏获取验证码
    

    5. 码UI点击事件处理

    页面肯定需要码UI, 代码比较简单, 只是控件使用和布局, 这里就不过多讲, 这里详细介绍下对应的点击事件处理, 每个按钮的 onPress 和输入框的 onChangeText中都要进行处理, 来获取对应的值和逻辑处理.

    (1). 首先需要在控件中定义点击事件和协议

    TextInput输入框控件, 可以使用onChangeText 来获取输入的内容:

    <TextInput style={styles.inputViewStyle}
                           onChangeText = {(text) => {
                              this.setState({userName: text});
                         }}
                          placeholder="请输入手机号"
                      />
    

    Button按钮, 可以使用 onPress 来处理点击事件:

     <ButtonView 
            btnName='获取验证码'
            btnStyle = {{width: 90,marginRight: 10, backgroundColor: '#D6D6D6'}}
                          onPress = {this._getPhoneCode}
            textStyle = {{color:'gray', justifyContent: 'flex-end',}}
      ></ButtonView>
    
    (2). 处理事件

    TextInput使用onChangeText,获取对应输入的值:

      _getUserName = () => {
        alert('A name was submitted: ' + this.state.userName);
      };
    

    Button使用onPress响应点击事件:

      _onClickLogin = () => {
        var usrInfo = "用户名:" + this.state.userName + "密码:" + this.state.userPW
        Alert.alert(usrInfo);
    
      };
    

    6. 网络请求

    本项目是基于登录来介绍, 在获取到对应的用户名密码或手机号验证码后, 需要请求接口传给后台来进行验证登录, 这里给大家介绍下fetch网络请求, 使用方便,简单易懂, 大家新手可以先使用这个, 后续介绍其它的方法.

     getUsrInfo = () => {
    
          fetch('http://...')
          .then((response) => response.json())
          .then((responseJson) => {
    
              this.state.userName = responseJson.status.code;
              this.state.userPW = responseJson.status.msg;
    
              this.setState({'userName':responseJson.status.code, 'userPW':responseJson.status.msg});
              
              return "responseJson.movies";
          })
          .catch((error) => {
              console.error(error);
          });
      }
    

    7. 注册

    因为登录页面需要使用到注册, 所以需要使用导航控制器来进行跳转, 这个上篇文章已经详细介绍过, 这里使用了RootView和自定义的RegistView.

    export default createStackNavigator({
      Home: {
        screen: RootView
      },
      Details:{
        screen: RegistView
      },
    });
    

    正常的注册页面和登录其实逻辑相似, 所以在项目中我就想再介绍一个知识, 就是在注册页面中, 为大家介绍下FlatList使用自定义cell的情况.

    (1)创建RegistCell

    //创建RegistCell
    export default class RegistCell extends React.Component {
    
        constructor(props) {
        super(props);
      }
    
      render() {
    
        // const {name, full_name} = this.props.item.item || {};
        let name = this.props.item.item.name;
        let full_name = this.props.item.item.owner.node_id;
    
        console.log(`===>message cell props, ${name}, ${full_name}`, this.props.item.item)
    
        return (
          <View style={styles.container}>
            <TouchableOpacity
              onPress={() => console.log('item clicked')}
              style={styles.touchable}>
              <View style={styles.touchableInside}>
                <Image
                  source={require('./img/graphql_wx.jpg')}
                  style={styles.image}
                  resizeMode={Image.resizeMode.stretch} />
                <View style={styles.insideView}>
                  <Text style={styles.insideText}>{name}</Text>
                  <Text style={styles.insideText}>{full_name}</Text>
                </View>
              </View>
            </TouchableOpacity>
          </View>
        );
      }
    }
    

    (2)创建完cell后, renderItem注册cell.

    renderItem = (item) => (
        <RegistCell item={item} />
      )
    

    (3)创建FlatList,调用自定义RegistCell

     render() {
    
        return (
    
          <View style={styles.container}>
            <Text>Message</Text>
            <FlatList
              data={this.state.data || []}
              renderItem={this.renderItem}
              keyExtractor={item => item.id}
              // onRefresh={this.handleRefresh}
              onEndReachedThreshold={0} />
          </View>
        );
      }
    

    简单的三步即可实现使用FlatList并自定义cell.

    到这里, 基于 React Navigation 的登录注册页面的所有地方就完成了, 想看详细代码和运行效果的可到GitHub下载代码: https://github.com/YTiOSer/YTReact-Native_LoginUI, 里面有完整的代码.

    您的支持是我的动力, 如果对您有所帮助的话, 不妨给个喜欢和关注哈!

    相关文章

      网友评论

      本文标题:React-Native 二、登录注册模块开发

      本文链接:https://www.haomeiwen.com/subject/sxkavftx.html