react native高仿微信app聊天室|RN羣聊|朋友圈

RN仿原生app開發, 基於react-native+react-navigation+react+redux+react-native-image-picker等技術實現的 仿微信app聊天RN_ChatRoom。實現了消息發送、textInput文本框混排emoj表情符、表情大圖、圖片選擇預覽、紅包、朋友圈等功能。

實現技術

  • MVVM框架:react / react-native / react-native-cli
  • 狀態管理:react-redux
  • 頁面導航:react-navigation
  • rn彈窗組件:rnPop
  • 打包工具:webpack 2.0
  • 輪播組件:react-native-swiper
  • 圖片/相冊:react-native-image-picker

效果預覽













package.json依賴注入

{
  "name": "RN_ChatRoom",
  "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"
  }
}複製代碼

基於react-navigation導航器自定義頂部導航條headerBar組件


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

    render() {
        /**
         * 更新
         * @param { navigation | 頁面導航 }
         * @param { title | 標題 }
         * @param { center | 標題是否居中 }
         * @param { search | 是否顯示搜索 }
         * @param { headerRight | 右側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>
                    {/* 標題 */}
                    { !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>
                        )
                    }
                    {/* 右側 */}
                    <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'}} />
                                            )
                                        }
                                        {/* 圓點 */}
                                        { 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()
    }
}
複製代碼

react-native本地存儲,async-storage

/**
 * @desc 本地存儲函數
 */

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
複製代碼

react-native實現全屏啓動頁,基於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 (
            <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(()=>{
                    // 跳轉頁面
                    util.navigationReset(this.props.navigation, (!err && object && object.hasLogin) ? 'Index' : 'Login')
                })
            }, 1500);
        })
    }
}複製代碼

react-native表情處理,emoj表情符

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

/**
 * 聊天模塊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
        })
    } 
}

// 發送消息
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)
}


// >>> 【選擇區功能模塊】------------------------------------------
// 選擇圖片
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)
        }
    })
}
複製代碼

附上最近項目實例,但願能喜歡😍😍 ~~~html

vue2.0聊天室:juejin.im/post/5ca975…vue

angular聊天室IM:juejin.im/post/5d2d9e…node

相關文章
相關標籤/搜索