taro+react聊天室|taro仿微信界面/朋友圈

4,823 阅读5分钟

前段时间有运用uni-app多端实践之仿抖音短视频/陌陌直播项目,最近一直在捣鼓taro多端开发,相比uniapp多端技术,taro开发多端应用复杂了不少,尤其编译到App端,更是各种坑。

基于Taro+react+redux+rn+taroPop多端应用开发taro-chatroom (仿微信聊天室)


taro技术栈:

  • 编码/技术:vscode + react/taro/redux/reactNative
  • iconfont图标:阿里字体图标库
  • 自定义顶部导航条 + Tabbar
  • 弹窗组件:taroPop(基于Taro封装自定义对话框)
  • 支持编译:H5端 + 小程序 + App端

















taro自定义导航栏模式

项目中为了效果统一,功能相对丰富些,顶部导航及底部tabbar均采用自定义组件模式,由于之前有分享文章,这里不详细介绍了。

顶部导航栏/底部tabbar组件  参看:Taro多端自定义导航栏Navbar+Tabbar实例

Taro自定义Modal组件  参看:Taro自定义模态框组件

入口app.jsx页面配置

/**
  * @desc   Taro入口页面 app.jsx
  * @about  Q:282310962  wx:xy190310
  */

import Taro, { Component } from '@tarojs/taro'
import Index from './pages/index'

// 引入状态管理redux
import { Provider } from '@tarojs/redux'
import { store } from './store'

// 引入样式
import './app.scss'
import './styles/fonts/iconfont.css'
import './styles/reset.scss'

class App extends Component {
  config = {
    pages: [
      'pages/auth/login/index',
      'pages/auth/register/index',
      'pages/index/index',
      ...
    ],
    window: {
      backgroundTextStyle: 'light',
      navigationBarBackgroundColor: '#fff',
      navigationBarTitleText: 'TaroChat',
      navigationBarTextStyle: 'black',
      navigationStyle: 'custom'
    }
  }
  
  // 在 App 类中的 render() 函数没有实际作用
  // 请勿修改此函数
  render () {
    return (
      <Provider store={store}>
        <Index />
      </Provider>
    )
  }
}

Taro.render(<App />, document.getElementById('app'))

taro登录/注册表单验证|redux状态管理|本地存储

在taro中获取表单input值也比较简单,直接使用onInput事件即可

<Input placeholder="请输入手机号/昵称" onInput={this.handleInput.bind(this, 'tel')} />

this.state = {
	tel: '',
	pwd: '',
}

handleInput = (key, e) => {
    this.setState({ [key]: e.detail.value })
}

通过上面的方法就有简单的获取input值了

return (
    <View className="taro__container flexDC bg-eef1f5">
        <Navigation background='#eef1f5' fixed />
        
        <ScrollView className="taro__scrollview flex1" scrollY>
            <View className="auth-lgreg">
                {/* logo */}
                <View className="auth-lgreg__slogan">
                    <View className="auth-lgreg__slogan-logo">
                        <Image className="auth-lgreg__slogan-logo__img" src={require('../../../assets/taro.png')} mode="aspectFit" />
                    </View>
                    <Text className="auth-lgreg__slogan-text">欢迎来到Taro-Chatroom</Text>
                </View>
                {/* 表单 */}
                <View className="auth-lgreg__forms">
                    <View className="auth-lgreg__forms-wrap">
                        <View className="auth-lgreg__forms-item">
                            <Input className="auth-lgreg__forms-iptxt flex1" placeholder="请输入手机号/昵称" onInput={this.handleInput.bind(this, 'tel')} />
                        </View>
                        <View className="auth-lgreg__forms-item">
                            <Input className="auth-lgreg__forms-iptxt flex1" placeholder="请输入密码" password onInput={this.handleInput.bind(this, 'pwd')} />
                        </View>
                    </View>
                    <View className="auth-lgreg__forms-action">
                        <TouchView onClick={this.handleSubmit}><Text className="auth-lgreg__forms-action__btn">登录</Text></TouchView>
                    </View>
                    <View className="auth-lgreg__forms-link">
                        <Text className="auth-lgreg__forms-link__nav">忘记密码</Text>
                        <Text className="auth-lgreg__forms-link__nav" onClick={this.GoToRegister}>注册账号</Text>
                    </View>
                </View>
            </View>
        </ScrollView>

        <TaroPop ref="taroPop" />
    </View>
)

/**
 * @tpl 登录模块
 */

import Taro from '@tarojs/taro'
import { View, Text, ScrollView, Image, Input, Button } from '@tarojs/components'

import './index.scss'

import { connect } from '@tarojs/redux'
import * as actions from '../../../store/action'...

class Login extends Taro.Component {
    config = {
        navigationBarTitleText: '登录'
    }
    constructor(props) {
        super(props)
        this.state = {
            tel: '',
            pwd: '',
        }
    }
    componentWillMount() {
        // 判断是否登录
        storage.get('hasLogin').then(res => {
            if(res && res.hasLogin) {
                Taro.navigateTo({url: '/pages/index/index'})
            }
        })
    }
    // 提交表单
    handleSubmit = () => {
        let taroPop = this.refs.taroPop
        let { tel, pwd } = this.state

        if(!tel) {
            taroPop.show({content: '手机号不能为空', time: 2})
        }else if(!util.checkTel(tel)) {
            taroPop.show({content: '手机号格式有误', time: 2})
        }else if(!pwd) {
            taroPop.show({content: '密码不能为空', time: 2})
        }else {
            // ...接口数据
            ...
            
            storage.set('hasLogin', { hasLogin: true })
            storage.set('user', { username: tel })
            storage.set('token', { token: util.setToken() })

            taroPop.show({
                skin: 'toast',
                content: '登录成功',
                icon: 'success',
                time: 2
            })
            
            ...
        }
    }
    
    render () {
        ...
    }
}

const mapStateToProps = (state) => {
    return {...state.auth}
}

export default connect(mapStateToProps, {
    ...actions
})(Login)

另外需要注意 taro中rn端不支持同步存储,只能改为setStorageSync异步存储了


/**
 * @desc Taro本地存储
 */

import Taro from '@tarojs/taro'

export default class Storage {
    static get(key) {
        return Taro.getStorage({ key }).then(res => res.data).catch(() => '')
    }

    static set(key, data){
        return Taro.setStorage({key: key, data: data}).then(res => res)
    }

    static del(key){
        Taro.removeStorage({key: key}).then(res => res)
    }

    static clear(){
        Taro.clearStorage()
    }
}

样式兼容处理

对于一些不希望编译到RN端样式,则通过如下包裹起来即可

/*postcss-pxtransform rn eject enable*//*postcss-pxtransform rn eject disable*/

rn端不兼容的样式,可通过scss提供的 @mixin 函数统一处理

/* 
 *  对于不兼容的样式,如RN不兼容border-right,可以通过mixin统一处理
 */

/**
 * RN 不支持针对某一边设置 style,即 border-bottom-style 会报错
 * 那么 border-bottom: 1px 就需要写成如下形式: border: 0 style color; border-bottom-width: 1px;
 */
@mixin border($dir, $width, $style, $color) {
    border: 0 $style $color;
    @each $d in $dir {
        #{border-#{$d}-width}: $width;
    }
}

/**
 * NOTE RN 无法通过 text-overflow 实现省略号,这些代码不会编译到 RN 中
 */
@mixin ellipsis {
    /*postcss-pxtransform rn eject enable*/
    overflow: hidden; white-space: nowrap; text-overflow: ellipsis;
    /*postcss-pxtransform rn eject disable*/
}

/**
 * NOTE 实现多行文本省略,RN 用 Text 标签的 numberOfLines={2},H5/小程序用 -webkit-line-clamp
 */
@mixin clamp($line) {
    /*postcss-pxtransform rn eject enable*/
    display: -webkit-box;
    overflow: hidden;
    -webkit-line-clamp:$line;
    /* autoprefixer: ignore next */
    -webkit-box-orient: vertical;
    /*postcss-pxtransform rn eject disable*/
}

/**
 * 对于不能打包到 RN 的样式,可以用 postcss 方式引入
 */
 @mixin eject($attr, $value) {
    /*postcss-pxtransform rn eject enable*/
    #{$attr}: $value;
    /*postcss-pxtransform rn eject disable*/
}

taro滚动至聊天信息底部


H5/小程序端则可通过获取createSelectorQuery 来实现滚动到聊天底部,由于RN端不支持createSelectorQuery,则只能另外兼容处理。


componentDidMount() {
    if(process.env.TARO_ENV === 'rn') {
        this.scrollMsgBottomRN()
    }else {
        this.scrollMsgBottom()
    }
}

// 滚动聊天底部
scrollMsgBottom = () => {
    let query = Taro.createSelectorQuery()
    query.select('#scrollview').boundingClientRect()
    query.select('#msglistview').boundingClientRect()
    query.exec((res) => {
        // console.log(res)
        if(res[1].height > res[0].height) {
            this.setState({ scrollTop: res[1].height - res[0].height })
        }
    })
}
scrollMsgBottomRN = (t) => {
    let that = this
    this._timer = setTimeout(() => {
        that.refs.ScrollViewRN.scrollToEnd({animated: false})
    }, t ? 16 : 0)
}

聊天表情部分则是使用emoj表情符,实现起来比较简单,则不多介绍了。

...

// 点击聊天消息区域
msgPanelClicked = () => {
	if(!this.state.showFootToolbar) return
	this.setState({ showFootToolbar: false })
}

// 表情、选择区切换
swtEmojChooseView = (index) => {
	this.setState({ showFootToolbar: true, showFootViewIndex: index })
}

// 底部表情tab切换
swtEmojTab = (index) => {
	let lists = this.state.emotionJson
	for(var i = 0, len = lists.length; i < len; i++) {
		lists[i].selected = false
	}
	lists[index].selected = true
	this.setState({ emotionJson: lists })
}


/* >>> 【编辑器/表情处理模块】------------------------------------- */
bindEditorInput = (e) => {
	this.setState({
		editorText: e.detail.value,
		editorLastCursor: e.detail.cursor
	})
}
bindEditorFocus = (e) => {
	this.setState({ editorLastCursor: e.detail.cursor })
}
bindEditorBlur = (e) => {
	this.setState({ editorLastCursor: e.detail.cursor })
}

handleEmotionTaped = (emoj) => {
	if(emoj == 'del') return
	// 在光标处插入表情
	let { editorText, editorLastCursor } = this.state
	let lastCursor = editorLastCursor ? editorLastCursor : editorText.length
	let startStr = editorText.substr(0, lastCursor)
	let endStr = editorText.substr(lastCursor)
	this.setState({
		editorText: startStr + `${emoj} ` + endStr
	})
}

...

emmm 夜深了,taro开发聊天应用就介绍到这里,后续会继续分享实例项目。😴😴

vue+uniapp仿抖音短视频/陌陌直播聊天室

react+redux仿微信网页端聊天|网页版聊天实例