亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

react-native聊天室|RN版聊天App仿微信實(shí)例|RN仿微信界面

 更新時(shí)間:2019年11月12日 08:49:43   作者:xiaoyan2017  
這篇文章主要介紹了react-native聊天室|RN版聊天App仿微信實(shí)例|RN仿微信界面,需要的朋友可以參考下

一、前言

9月,又到開(kāi)學(xué)的季節(jié)。為每個(gè)一直默默努力的自己點(diǎn)贊!最近都沉浸在react native原生app開(kāi)發(fā)中,之前也有使用vue/react/angular等技術(shù)開(kāi)發(fā)過(guò)聊天室項(xiàng)目,另外還使用RN技術(shù)做了個(gè)自定義模態(tài)彈窗rnPop組件。

一、項(xiàng)目簡(jiǎn)述

基于react+react-native+react-navigation+react-redux+react-native-swiper+rnPop等技術(shù)開(kāi)發(fā)的仿微信原生App界面聊天室——RN_ChatRoom,實(shí)現(xiàn)了原生app啟動(dòng)頁(yè)、AsyncStorage本地存儲(chǔ)登錄攔截、集成rnPop模態(tài)框功能(仿微信popupWindow彈窗菜單)、消息觸摸列表、發(fā)送消息、表情(動(dòng)圖),圖片預(yù)覽,拍攝圖片、發(fā)紅包、仿微信朋友圈等功能。

二、技術(shù)點(diǎn)

  • MVVM框架:react / react-native / react-native-cli
  • 狀態(tài)管理:react-redux / redux頁(yè)面導(dǎo)航:react-navigationrn
  • 彈窗組件:rnPop打包工具:webpack 2.0輪播組件:react-native-swiper
  • 圖片/相冊(cè):react-native-image-picker
{
 "name": "RN_ChatRoom",
 "version": "0.0.1",
 "aboutMe": "QQ:282310962 、 wx:xy190310",
 "dependencies": {
  "react": "16.8.6",
  "react-native": "0.60.4"
 },
 "devDependencies": {
  "@babel/core": "^7.5.5",
  "@babel/runtime": "^7.5.5",
  "@react-native-community/async-storage": "^1.6.1",
  "@react-native-community/eslint-config": "^0.0.5",
  "babel-jest": "^24.8.0",
  "eslint": "^6.1.0",
  "jest": "^24.8.0",
  "metro-react-native-babel-preset": "^0.55.0",
  "react-native-gesture-handler": "^1.3.0",
  "react-native-image-picker": "^1.0.2",
  "react-native-swiper": "^1.5.14",
  "react-navigation": "^3.11.1",
  "react-redux": "^7.1.0",
  "react-test-renderer": "16.8.6",
  "redux": "^4.0.4",
  "redux-thunk": "^2.3.0"
 },
 "jest": {
  "preset": "react-native"
 }
}

◆ App全屏幕啟動(dòng)頁(yè)splash模板

react-native如何全屏啟動(dòng)? 設(shè)置StatusBar頂部條背景為透明 translucent={true},并配合RN動(dòng)畫Animated

/**
 * @desc 啟動(dòng)頁(yè)面
 */

import React, { Component } from 'react'
import { StatusBar, Animated, View, Text, Image } from 'react-native'

export default class Splash extends Component{
  constructor(props){
    super(props)
    this.state = {
      animFadeIn: new Animated.Value(0),
      animFadeOut: new Animated.Value(1),
    }
  }

  render(){
    return (
      <Animated.View style={[GStyle.flex1DC_a_j, {backgroundColor: '#1a4065', opacity: this.state.animFadeOut}]}>
        <StatusBar backgroundColor='transparent' barStyle='light-content' translucent={true} />

        <View style={GStyle.flex1_a_j}>
          <Image source={require('../assets/img/ic_default.jpg')} style={{borderRadius: 100, width: 100, height: 100}} />
        </View>
        <View style={[GStyle.align_c, {paddingVertical: 20}]}>
          <Text style={{color: '#dbdbdb', fontSize: 12, textAlign: 'center',}}>RN-ChatRoom v1.0.0</Text>
        </View>
      </Animated.View>
    )
  }

  componentDidMount(){
    // 判斷是否登錄
    storage.get('hasLogin', (err, object) => {
      setTimeout(() => {
        Animated.timing(
          this.state.animFadeOut, {duration: 300, toValue: 0}
        ).start(()=>{
          // 跳轉(zhuǎn)頁(yè)面
          util.navigationReset(this.props.navigation, (!err && object && object.hasLogin) ? 'Index' : 'Login')
        })
      }, 1500);
    })
  }
}

◆ RN本地存儲(chǔ)技術(shù)async-storage

/**
 * @desc 本地存儲(chǔ)函數(shù)
 */

import AsyncStorage from '@react-native-community/async-storage'

export default class Storage{
  static get(key, callback){
    return AsyncStorage.getItem(key, (err, object) => {
      callback(err, JSON.parse(object))
    })
  }

  static set(key, data, callback){
    return AsyncStorage.setItem(key, JSON.stringify(data), callback)
  }

  static del(key){
    return AsyncStorage.removeItem(key)
  }

  static clear(){
    AsyncStorage.clear()
  }
}

global.storage = Storage

聲明全局global變量,只需在App.js頁(yè)面一次引入、多個(gè)頁(yè)面均可調(diào)用。

storage.set('hasLogin', { hasLogin: true })
storage.get('hasLogin', (err, object) => { ... })

◆ App主頁(yè)面模板及全局引入組件

import React, { Fragment, Component } from 'react'
import { StatusBar } from 'react-native'

// 引入公共js
import './src/utils/util'
import './src/utils/storage'

// 導(dǎo)入樣式
import './src/assets/css/common'
// 導(dǎo)入rnPop彈窗
import './src/assets/js/rnPop/rnPop.js'

// 引入頁(yè)面路由
import PageRouter from './src/router'

class App extends Component{
 render(){
  return (
   <Fragment>
    {/* <StatusBar backgroundColor={GStyle.headerBackgroundColor} barStyle='light-content' /> */}

    {/* 頁(yè)面 */}
    <PageRouter />

    {/* 彈窗模板 */}
    <RNPop />
   </Fragment>
  )
 }
}

export default App

◆ react-navigation頁(yè)面導(dǎo)航器/地址路由、底部tabbar

由于react-navigation官方頂部導(dǎo)航器不能滿足需求,如是自己封裝了一個(gè),功能效果有些類似微信導(dǎo)航。

export default class HeaderBar extends Component {
  constructor(props){
    super(props)
    this.state = {
      searchInput: ''
    }
  }

  render() {
    /**
     * 更新
     * @param { navigation | 頁(yè)面導(dǎo)航 }
     * @param { title | 標(biāo)題 }
     * @param { center | 標(biāo)題是否居中 }
     * @param { search | 是否顯示搜索 }
     * @param { headerRight | 右側(cè)Icon按鈕 }
     */
    let{ navigation, title, bg, center, search, headerRight } = this.props

    return (
      <View style={GStyle.flex_col}>
        <StatusBar backgroundColor={bg ? bg : GStyle.headerBackgroundColor} barStyle='light-content' translucent={true} />
        <View style={[styles.rnim__topBar, GStyle.flex_row, {backgroundColor: bg ? bg : GStyle.headerBackgroundColor}]}>
          {/* 返回 */}
          <TouchableOpacity style={[styles.iconBack]} activeOpacity={.5} onPress={this.goBack}><Text style={[GStyle.iconfont, GStyle.c_fff, GStyle.fs_18]}>&#xe63f;</Text></TouchableOpacity>
          {/* 標(biāo)題 */}
          { !search && center ? <View style={GStyle.flex1} /> : null }
          {
            search ? 
            (
              <View style={[styles.barSearch, GStyle.flex1, GStyle.flex_row]}>
                <TextInput onChangeText={text=>{this.setState({searchInput: text})}} style={styles.barSearchText} placeholder='搜索' placeholderTextColor='rgba(255,255,255,.6)' />
              </View>
            )
            :
            (
              <View style={[styles.barTit, GStyle.flex1, GStyle.flex_row, center ? styles.barTitCenter : null]}>
                { title ? <Text style={[styles.barCell, {fontSize: 16, paddingLeft: 0}]}>{title}</Text> : null }
              </View>
            )
          }
          {/* 右側(cè) */}
          <View style={[styles.barBtn, GStyle.flex_row]}>
            { 
              !headerRight ? null : headerRight.map((item, index) => {
                return(
                  <TouchableOpacity style={[styles.iconItem]} activeOpacity={.5} key={index} onPress={()=>item.press ? item.press(this.state.searchInput) : null}>
                    {
                      item.type === 'iconfont' ? item.title : (
                        typeof item.title === 'string' ? 
                        <Text style={item.style ? item.style : null}>{`${item.title}`}</Text>
                        :
                        <Image source={item.title} style={{width: 24, height: 24, resizeMode: 'contain'}} />
                      )
                    }
                    {/* 圓點(diǎn) */}
                    { item.badge ? <View style={[styles.iconBadge, GStyle.badge]}><Text style={GStyle.badge_text}>{item.badge}</Text></View> : null }
                    { item.badgeDot ? <View style={[styles.iconBadgeDot, GStyle.badge_dot]}></View> : null }
                  </TouchableOpacity>
                )
              })
            }
          </View>
        </View>
      </View>
    )
  }

  goBack = () => {
    this.props.navigation.goBack()
  }
}
// 創(chuàng)建底部TabBar
const tabNavigator = createBottomTabNavigator(
  // tabbar路由(消息、通訊錄、我)
  {
    Index: {
      screen: Index,
      navigationOptions: ({navigation}) => ({
        tabBarLabel: '消息',
        tabBarIcon: ({focused, tintColor}) => (
          <View>
            <Text style={[ GStyle.iconfont, GStyle.fs_20, {color: (focused ? tintColor : '#999')} ]}>&#xe642;</Text>
            <View style={[GStyle.badge, {position: 'absolute', top: -2, right: -15,}]}><Text style={GStyle.badge_text}>12</Text></View>
          </View>
        )
      })
    },
    Contact: {
      screen: Contact,
      navigationOptions: {
        tabBarLabel: '通訊錄',
        tabBarIcon: ({focused, tintColor}) => (
          <View>
            <Text style={[ GStyle.iconfont, GStyle.fs_20, {color: (focused ? tintColor : '#999')} ]}>&#xe640;</Text>
          </View>
        )
      }
    },
    Ucenter: {
      screen: Ucenter,
      navigationOptions: {
        tabBarLabel: '我',
        tabBarIcon: ({focused, tintColor}) => (
          <View>
            <Text style={[ GStyle.iconfont, GStyle.fs_20, {color: (focused ? tintColor : '#999')} ]}>&#xe61e;</Text>
            <View style={[GStyle.badge_dot, {position: 'absolute', top: -2, right: -6,}]}></View>
          </View>
        )
      }
    }
  },
  // tabbar配置
  {
    ...
  }
)

◆ RN聊天頁(yè)面功能模塊

1、表情處理:原本是想著使用圖片表情gif,可是在RN里面textInput文本框不能插入圖片,只能通過(guò)定義一些特殊字符 :66: (:12 [奮斗] 解析表情,處理起來(lái)有些麻煩,而且圖片多了影響性能,如是就改用emoj表情符。

faceList: [
  {
    nodes: [
      '🙂','😁','😋','😎','😍','😘','😗',
      '😃','😂','🤣','😅','😉','😊','🤗',
      '🤔','😐','😑','😶','🙄','😏','del',
    ]
  },
  ...
  {
    nodes: [
      '👓','👄','💋','👕','👙','👜','👠',
      '👑','🎓','💄','💍','🌂','👧🏼','👨🏼',
      '👵🏻','👴🏻','👨‍🌾','👨🏼‍🍳','👩🏻‍🍳','👨🏽‍✈️','del',
    ]
  },
  ...
]

2、光標(biāo)定位:在指定光標(biāo)處插入內(nèi)容,textInput提供了光標(biāo)起始位置

let selection = this.textInput._lastNativeSelection || null;
this.textInput.setNativeProps({
  selection : { start : xxx, end : xxx}
})

3、textInput判斷內(nèi)容是否為空,過(guò)濾空格、回車

isEmpty = (html) => {
  return html.replace(/\r\n|\n|\r/, "").replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, "") == ""
}

/**
 * 聊天模塊JS----------------------------------------------------
 */
// ...滾動(dòng)至聊天底部
scrollToBottom = (t) => {
  let that = this
  this._timer = setTimeout(() => {
    that.refs.scrollView.scrollToEnd({animated: false})
  }, t ? 16 : 0);
}

// ...隱藏鍵盤
hideKeyboard = () => {
  Keyboard && Keyboard.dismiss()
}

// 點(diǎn)擊表情
handlePressEmotion = (img) => {
  if(img === 'del') return

  let selection = this.editorInput._lastNativeSelection || null;
  if (!selection){
    this.setState({
      editorText : this.state.editorText + `${img}`,
      lastRange: this.state.editorText.length
    })
  }
  else {
    let startStr = this.state.editorText.substr(0 , this.state.lastRange ? this.state.lastRange : selection.start)
    let endStr = this.state.editorText.substr(this.state.lastRange ? this.state.lastRange : selection.end)
    this.setState({
      editorText : startStr + `${img}` + endStr,
      lastRange: (startStr + `${img}`).length
    })
  } 
}

// 發(fā)送消息
isEmpty = (html) => {
  return html.replace(/\r\n|\n|\r/, "").replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, "") == ""
}
handleSubmit = () => {
  // 判斷是否為空值
  if(this.isEmpty(this.state.editorText)) return

  let _msg = this.state.__messageJson
  let _len = _msg.length
  // 消息隊(duì)列
  let _data = {
    id: `msg${++_len}`,
    msgtype: 3,
    isme: true,
    avator: require('../../../assets/img/uimg/u__chat_img11.jpg'),
    author: '王梅(Fine)',
    msg: this.state.editorText,
    imgsrc: '',
    videosrc: ''
  }
  _msg = _msg.concat(_data)
  this.setState({ __messageJson: _msg, editorText: '' })

  this.scrollToBottom(true)
}


// >>> 【選擇區(qū)功能模塊】------------------------------------------
// 選擇圖片
handleLaunchImage = () => {
  let that = this

  ImagePicker.launchImageLibrary({
    // title: '請(qǐng)選擇圖片來(lái)源',
    // cancelButtonTitle: '取消',
    // takePhotoButtonTitle: '拍照',
    // chooseFromLibraryButtonTitle: '相冊(cè)圖片',
    // customButtons: [
    //   {name: 'baidu', title: 'baidu.com圖片'},
    // ],
    // cameraType: 'back',
    // mediaType: 'photo',
    // videoQuality: 'high',
    // maxWidth: 300,
    // maxHeight: 300,
    // quality: .8,
    // noData: true,
    storageOptions: {
      skipBackup: true,
    },
  }, (response) => {
    // console.log(response)

    if(response.didCancel){
      console.log('user cancelled')
    }else if(response.error){
      console.log('ImagePicker Error')
    }else{
      let source = { uri: response.uri }
      // let source = {uri: 'data:image/jpeg;base64,' + response.data}
      that.setState({ imgsrc: source })

      that.scrollToBottom(true)
    }
  })
}

總結(jié)

以上所述是小編給大家介紹的react-native聊天室|RN版聊天App仿微信實(shí)例|RN仿微信界面,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

相關(guān)文章

  • React組件useReducer的講解與使用

    React組件useReducer的講解與使用

    在React函數(shù)式組件中,我們可以通過(guò)useState()來(lái)創(chuàng)建state,這種state創(chuàng)建方式會(huì)給我們返回兩個(gè)東西state和setState()。
    2023-04-04
  • React項(xiàng)目搭建與Echarts工具使用詳解

    React項(xiàng)目搭建與Echarts工具使用詳解

    這篇文章主要介紹了React項(xiàng)目搭建與Echarts工具使用詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-03-03
  • React代碼分割的實(shí)現(xiàn)方法介紹

    React代碼分割的實(shí)現(xiàn)方法介紹

    雖然一直有做react相關(guān)的優(yōu)化,按需加載、dll 分離、服務(wù)端渲染,但是從來(lái)沒(méi)有從路由代碼分割這一塊入手過(guò),所以下面這篇文章主要給大家介紹了關(guān)于React中代碼分割的方式,需要的朋友可以參考下
    2022-12-12
  • 在React Native中添加自定義字體的方法詳解

    在React Native中添加自定義字體的方法詳解

    在這篇指南中,我們將探索使用 Google Fonts 在 React Native 應(yīng)用中添加自定義字體的方法,字體是優(yōu)秀用戶體驗(yàn)的基石,使用定制字體可以為你的應(yīng)用程序提供獨(dú)特的身份,需要的朋友可以參考下
    2024-02-02
  • webpack打包react項(xiàng)目的實(shí)現(xiàn)方法

    webpack打包react項(xiàng)目的實(shí)現(xiàn)方法

    這篇文章主要介紹了webpack打包react項(xiàng)目的實(shí)現(xiàn)方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • ReactJs實(shí)現(xiàn)樹(shù)形結(jié)構(gòu)的數(shù)據(jù)顯示的組件的示例

    ReactJs實(shí)現(xiàn)樹(shù)形結(jié)構(gòu)的數(shù)據(jù)顯示的組件的示例

    本篇文章主要介紹了ReactJs實(shí)現(xiàn)樹(shù)形結(jié)構(gòu)的數(shù)據(jù)顯示的組件的示例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2017-08-08
  • 在react項(xiàng)目中使用antd的form組件,動(dòng)態(tài)設(shè)置input框的值

    在react項(xiàng)目中使用antd的form組件,動(dòng)態(tài)設(shè)置input框的值

    這篇文章主要介紹了在react項(xiàng)目中使用antd的form組件,動(dòng)態(tài)設(shè)置input框的值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-10-10
  • React項(xiàng)目打包發(fā)布到Tomcat頁(yè)面空白問(wèn)題及解決

    React項(xiàng)目打包發(fā)布到Tomcat頁(yè)面空白問(wèn)題及解決

    這篇文章主要介紹了React項(xiàng)目打包發(fā)布到Tomcat頁(yè)面空白問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • 深入理解React中何時(shí)使用箭頭函數(shù)

    深入理解React中何時(shí)使用箭頭函數(shù)

    對(duì)于剛學(xué)前端的大家來(lái)說(shuō),對(duì)于React中的事件監(jiān)聽(tīng)寫法有所疑問(wèn)很正常,特別是React中箭頭函數(shù)使用這塊,下面這篇文章主要給大家深入的講解了關(guān)于React中何時(shí)使用箭頭函數(shù)的相關(guān)資料,需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-08-08
  • React+Electron快速創(chuàng)建并打包成桌面應(yīng)用的實(shí)例代碼

    React+Electron快速創(chuàng)建并打包成桌面應(yīng)用的實(shí)例代碼

    這篇文章主要介紹了React+Electron快速創(chuàng)建并打包成桌面應(yīng)用,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-12-12

最新評(píng)論