ReactNative聊天APP实战|仿微信聊天/朋友圈/红包界面

项目简介

最近一直在研究RN技术,想着找个项目练练手,之前就有使用vue、react技术开发过聊天项目,这次就使用reactNative技术开发个仿微信RN版。是基于 react-native+react-navigation+react-redux+react-native-image-picker+rnPop 等技术实现开发的仿微信原生APP聊天项目,该项目从搭建到开发完 花了半个月,主要是白天太忙,只能晚上抽时间弄,开发过程采坑不少,不过通过一些技术论坛把问题都一 一撸顺了。

  

技术选择

  • RN脚手架:react / react-native / react-native-cli
  • 状态管理:react-redux
  • 页面导航:react-navigation
  • rn 弹窗组件:rnPop
  • 打包工具:webpack 2.0
  • 轮播组件:react-native-swiper
  • 图片 /相册:react-native-image-picker
{
  "name": "RN_ChatRoom",
  "aboutMe": "QQ:282310962",
  
  "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"
  }
}

  

  

  

  

  

  

RN中写公共样式

新建common.js公共样式库,通过react native中提供的global全局变量,在app.js中一次引入,然后所有页面均可以调用。

<View style={[GStyle.borT, GStyle.bg_45cff5, GStyle.mt_10]}></View>
global.GStyle = {
    pixel: 1 / PixelRatio.get(),
	
    // 边框
    borT: {borderTopWidth: 1 / PixelRatio.get(), borderTopColor: '#dedede',},
    borB: {borderBottomWidth: 1 / PixelRatio.get(), borderBottomColor: '#dedede',},

    /* __ 布局控制 */
    align_l: {textAlign: 'left'},
    align_c: {textAlign: 'center'},
    align_r: {textAlign: 'right'},

    pos_rel: {position: 'relative'},
    pos_abs: {position: 'absolute'},

    /* __ 颜色(背景、文字) */
    bg_fff: {backgroundColor: '#fff'},
    bg_45cff5: {backgroundColor: '#45cff5'},
    c_fff: {color: '#fff'},
    c_999: {color: '#999'},
    c_45cff5: {color: '#45cff5'},

    /* __ 字号 */
    fs_14: {fontSize: 14},
    fs_16: {fontSize: 16},
    fs_20: {fontSize: 20},
    fs_24: {fontSize: 24},

    /* __ 字体 */
    ff_ic: {fontFamily: 'iconfont'},
    ff_ar: {fontFamily: 'arial'},
    iconfont: {fontFamily: 'iconfont', fontSize: 16,},

    /* __ 间距( 5/10/15/20/25/30/50 ) */
    mt_10: {marginTop: 10}, mt_15: {marginTop: 15}, mt_20: {marginTop: 20},
    mb_10: {marginBottom: 10}, mb_15: {marginBottom: 15}, mb_20: {marginBottom: 20},

    /* __ 行高 */
    lh_20: {lineHeight: 20},
    lh_25: {lineHeight: 25},
    lh_30: {lineHeight: 30},
    lh_35: {lineHeight: 35},
    lh_40: {lineHeight: 40},

    flex1: {flex: 1},
    flex2: {flex: 2},
	
    flex_alignC: {alignItems: 'center'},
    flex_alignT: {alignItems: 'flex-start'},
    flex_alignB: {alignItems: 'flex-end'},
}

RN实现app全屏启动制作

react native实现沉浸式效果(类似京东、淘宝首页顶部),只需把 StatusBar 设置为透明,这样状态栏和背景页面一体了。

<statusbar backgroundcolor="transparent" barstyle="light-content" translucent="{true}"></statusbar>

export default class Splash extends Component{
    constructor(props){
        super(props)
        this.state = {
            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(()=>{
					this.props.navigation.navigate('Index')
                })
            }, 1500);
        })
    }
}

RN自定义顶部条headerBar

react-navigation自带的顶部导航栏一般能满足项目需求,可是一些特殊自定义化的项目,就只能自己定制开发了。如是基于react-navigation做了个自定义顶部导航组件。

支持多种属性配置,调用十分方便,<HeaderBar navigation={this.props.navigation} center search headerRight={[{,...},{....}]} />

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()
    }
}

RN自定义Modal弹窗组件(仿微信/ios效果)

项目中用到的弹窗是自己基于Modal开发的自定义弹窗组件|dialog对话框|toast提示,支持多种调用方式,具体的可以去看看这篇文章介绍?  https://www.cnblogs.com/xiaoyan2017/p/11292096.html

static defaultProps = {
	isVisible: false,       //弹窗显示

	title: '',              //标题
	content: '',            //内容
	style: null,            //自定义弹窗样式 {object}
	contentStyle: null,     //内容样式
	skin: '',               //自定义弹窗风格
	icon: '',               //自定义弹窗图标

	shade: true,            //遮罩层
	shadeClose: true,       //点击遮罩层关闭
	opacity: '',            //遮罩层透明度
	time: 0,                //弹窗自动关闭秒数
	xtime: false,           //显示关闭秒数
	end: null,              //销毁弹窗时回调函数

	anim: 'scaleIn',        //弹窗动画( scaleIn / fadeIn / top / bottom / left / right )
	follow: null,			//跟随定位(适用于在长按位置定位弹窗)
	position: '',           //弹窗位置

	btns: null,             //弹窗按钮(不设置则不显示按钮)[{...options}, {...options}]
}

RN聊天表情、TextInput光标处理

  • 在社交软件中,基本上都会有 emoji 表情功能。聊天中要显示文字和 emoji 表情的混排(上图所示),在原生 iOS 开发时,可以用富文本 NSAttributedString 实现,安卓中用 SpannableString 实现。不过在 ReactNative 中,貌似没有直接的现成实现方案。 

方法一: 通过特殊符处理,[哭泣] (:88 类似这样的,处理起来比较麻烦,而且图片多了会影响页面性能。 
方法二: 使用 emoj 表情符,这种方式处理比较简单,网上很多表情符可用,而且不需要特殊处理,性能也还不错。如果要求不高,推荐这种方式。

faceList: [
	{
		nodes: [
			'?','?','?','?','?','?','?',
			'?','?','?','?','?','?','?',
			'?','?','?','?','?','?','del',
		]
	},
	{
		nodes: [
			'?','?','?','?','?','?','?',
			'?','?','?','?','?','??','??',
			'??','??','?‍?','??‍?','??‍?','??‍✈️','del',
		]
	},
	...
]
  • 如何把字符插入到光标所在位置,就需要获取光标位置

函数:setNativeProps用于设置光标位置。传参为{selection : { start : start, end : end}},指定光标的开始和结束。如果start和end不等,这说明start->end位置的内容为选中状态。this.editorInput.setNativeProps({selection : { start : start, end : end}})
属性:_lastNativeSelection是个对象,包含光标的开始和结束位置。{start:start end: end}

好了,今天的分享就到这里,希望以后能给大家分享更多知识。希望能喜欢??

原创文章 19 获赞 56 访问量 7万+

猜你喜欢

转载自blog.csdn.net/yanxinyun1990/article/details/100573360
今日推荐