本篇文章給大家分享的是有關(guān)使用react native 怎么實現(xiàn)一個微信聊天室,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供安吉網(wǎng)站建設(shè)、安吉做網(wǎng)站、安吉網(wǎng)站設(shè)計、安吉網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、安吉企業(yè)網(wǎng)站模板建站服務(wù),十年安吉做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
、技術(shù)點
MVVM框架:react / react-native / react-native-cli
狀態(tài)管理:react-redux / redux
頁面導(dǎo)航:react-navigation
rn彈窗組件:rnPop
打包工具:webpack 2.0
輪播組件:react-native-swiper
圖片/相冊: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全屏幕啟動頁splash模板
react-native
如何全屏啟動? 設(shè)置StatusBar頂部條背景為透明 translucent={true},
并配合RN動畫Animated
/** * @desc 啟動頁面 */ 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 () } componentDidMount(){ // 判斷是否登錄 storage.get('hasLogin', (err, object) => { setTimeout(() => { Animated.timing( this.state.animFadeOut, {duration: 300, toValue: 0} ).start(()=>{ // 跳轉(zhuǎn)頁面 util.navigationReset(this.props.navigation, (!err && object && object.hasLogin) ? 'Index' : 'Login') }) }, 1500); }) } } RN-ChatRoom v1.0.0
◆ RN本地存儲技術(shù)async-storage
/** * @desc 本地存儲函數(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頁面一次引入、多個頁面均可調(diào)用。
storage.set('hasLogin', { hasLogin: true }) storage.get('hasLogin', (err, object) => { ... })
◆ App主頁面模板及全局引入組件
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' // 引入頁面路由 import PageRouter from './src/router' class App extends Component{ render(){ return ({/* ) } } export default App*/} {/* 頁面 */} {/* 彈窗模板 */}
◆ react-navigation頁面導(dǎo)航器/地址路由、底部tabbar
由于react-navigation官方頂部導(dǎo)航器不能滿足需求,如是自己封裝了一個,功能效果有些類似微信導(dǎo)航。
export default class HeaderBar extends Component { constructor(props){ super(props) this.state = { searchInput: '' } } render() { /** * 更新 * @param { navigation | 頁面導(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 () } goBack = () => { this.props.navigation.goBack() } } {/* 返回 */} {/* 標(biāo)題 */} { !search && center ? : null } { search ? ( ) : ( {this.setState({searchInput: text})}} style={styles.barSearchText} placeholder='搜索' placeholderTextColor='rgba(255,255,255,.6)' /> { title ? ) } {/* 右側(cè) */}{title} : null }{ !headerRight ? null : headerRight.map((item, index) => { return( item.press ? item.press(this.state.searchInput) : null}> { item.type === 'iconfont' ? item.title : ( typeof item.title === 'string' ? ) }) }{`${item.title}`} :) } {/* 圓點 */} { item.badge ? : null } { item.badgeDot ? {item.badge} : null }
// 創(chuàng)建底部TabBar const tabNavigator = createBottomTabNavigator( // tabbar路由(消息、通訊錄、我) { Index: { screen: Index, navigationOptions: ({navigation}) => ({ tabBarLabel: '消息', tabBarIcon: ({focused, tintColor}) => () }) }, Contact: { screen: Contact, navigationOptions: { tabBarLabel: '通訊錄', tabBarIcon: ({focused, tintColor}) => ( 12 ) } }, Ucenter: { screen: Ucenter, navigationOptions: { tabBarLabel: '我', tabBarIcon: ({focused, tintColor}) => ( ) } } }, // tabbar配置 { ... } )
◆ RN聊天頁面功能模塊
1、表情處理:原本是想著使用圖片表情gif,可是在RN里面textInput文本框不能插入圖片,只能通過定義一些特殊字符 :66: (:12 [奮斗] 解析表情,處理起來有些麻煩,而且圖片多了影響性能,如是就改用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)容是否為空,過濾空格、回車
isEmpty = (html) => { return html.replace(/\r\n|\n|\r/, "").replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, "") == "" }
/** * 聊天模塊JS---------------------------------------------------- */ // ...滾動至聊天底部 scrollToBottom = (t) => { let that = this this._timer = setTimeout(() => { that.refs.scrollView.scrollToEnd({animated: false}) }, t ? 16 : 0); } // ...隱藏鍵盤 hideKeyboard = () => { Keyboard && Keyboard.dismiss() } // 點擊表情 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 // 消息隊列 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: '請選擇圖片來源', // cancelButtonTitle: '取消', // takePhotoButtonTitle: '拍照', // chooseFromLibraryButtonTitle: '相冊圖片', // 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) } }) }
以上就是使用react native 怎么實現(xiàn)一個微信聊天室,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。