基于vite4.x构建react18项目,实现仿微信界面聊天实例。
基于
React18、React-Router v6、React-Hooks、Zustand、React-Vant、Vite4.x等技术实现仿制微信App聊天室。实现了发送图文消息、图片/视频预览、红包/朋友圈等功能。
技术选型
- 编码开发:VScode
- 框架技术:React18+React-dom
- 构建工具:Vite4.x
- UI组件库:react-vant (有赞react移动库)
- 状态管理:Zustand^4.3.9
- 路由管理:react-router-dom^6.14.2
- className混合:clsx^2.0.0
- 弹框组件:rcpop (基于react18 hooks自定义手机端弹框组件)
react-chat采用react-hooks函数组件编码开发页面,支持路由集中式配置处理。
项目构建目录
React18自定义弹框组件RcPop
rcpop一款基于react18 hooks开发的手机端多功能弹框组件,支持20+参数配置、组件式+函数式混合调用。
React18-hooks自定义导航栏Navbar+菜单栏Tabbar
项目中导航栏/菜单栏 使用react18自定义组件实现功能效果。
navbar.jsx组件模板
function Navbar(props) {
const {
// 是否显示返回键
back = true,
// 自定义返回图标
backIco,
// 自定义返回文字
backText,
// 标题
title,
// 搜索区
search,
// 左侧自定义区
left,
// 右侧自定义区
right,
// 标题颜色
color = '#fff',
// 背景色
bgcolor = '#139fcc',
// 标题是否居中
center,
// 是否固定
fixed,
// 背景镂空透明
transparent,
// 层叠
zIndex = 2023,
className,
...rest
} = props
const handleBack = () => {
window.history.back()
}
return (
<div {...rest} className={clsx('rc__navbar', className, {'fixed': fixed, 'transparent fixed': transparent})}>
<div className="rc__navbar-wrap flexbox flex-alignc" style={{'background': bgcolor, 'color': color, 'zIndex': zIndex}}>
{/* 返回 */}
{ isTrue(back) && (
<div className="action rc__navbar-action__left" onClick={handleBack}>
{ backIco ? backIco : <i className="iconfont ve-icon-left"></i> }
{backText}
</div>
)}
{left}
{/* 标题 */}
{ !search && <div className={clsx('rc__navbar-title', {'center': center})}>{title}</div> }
{/* 搜索框 */}
{ search && <div className="action rc__navbar-action__search">{search}</div> }
{/* 右侧 */}
<div className="action rc__navbar-action__right">{right}</div>
</div>
</div>
)
}
export default Navbar
调用非常简单,如下:
<Navbar
back={false}
bgcolor="linear-gradient(to right, #139fcc, #bc8bfd)"
title={<span className="ff-gg">React18-Chat</span>}
fixed
right={
<>
<i className="iconfont ve-icon-search"></i>
<i className="iconfont ve-icon-plus-circle-o ml-30"></i>
</>
}
/>
tabbar.jsx组件模板
function Tabbar(props) {
const {
// 当前选项
current = 0,
// 背景色
bgcolor = '#fff',
// 颜色
color = '#999',
// 激活颜色
activeColor = '#139fcc',
// 是否固定
fixed,
// 背景镂空透明
transparent,
// 层叠
zIndex = 2023,
// tab选项
tabs = [
{
path: '/',
icon: 've-icon-message',
title: '消息',
badge: 2
},
{
path: '/contact',
icon: 've-icon-book',
title: '通讯录'
},
{
path: '/my',
icon: 've-icon-user',
title: '我的',
dot: true
}
],
onClick = () => {},
className,
...rest
} = props
const [tabIndex, setTabIndex] = useState(current)
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
const { pathname } = location
tabs.map((item, index) => {
if(item.path == pathname) {
setTabIndex(index)
}
})
}, [current, tabs])
const handleTabs = (index, item) => {
setTabIndex(index)
onClick?.(index)
if(item?.path) {
navigate(item?.path)
}
}
return (
<div {...rest} className={clsx('rc__tabbar', className, {'fixed': fixed, 'transparent fixed': transparent})}>
<div className="rc__tabbar-wrap flexbox flex-alignc" style={{'background': bgcolor, 'zIndex': zIndex}}>
{ tabs.map((item, index) => {
return (
<div key={index} className={clsx('tabitem', {'on': tabIndex == index})} onClick={()=>handleTabs(index, item)}>
<div className={clsx('ico', {'dock': item.dock})}>
{ item.dock && <i className="dock-bg" style={{'background': item.dockBg ? item.dockBg : activeColor}}></i> }
{ item.icon && <i className={clsx('iconfont', item.icon)} style={{'color': (tabIndex == index && !item.dock ? activeColor : color), 'fontSize': item.iconSize}}></i> }
{ item.img && <img className="iconimg" src={tabIndex == index && !item.dock ? item.activeImg : item.img} style={{'fontSize': item.iconSize}} /> }
{ item.badge && <em className="rc__badge">{item.badge}</em> }
{ item.dot && <em className="rc__badge-dot"></em> }
</div>
<div className="txt" style={{'color': (tabIndex == index ? activeColor: color)}}>{item.title}</div>
</div>
)
})}
</div>
</div>
)
}
export default Tabbar
App.jsx模板配置
import { HashRouter } from 'react-router-dom'
// 引入useRoutes集中式路由配置
import Router from './router'
// 引入fontSize
import '@assets/js/fontSize'
function App() {
return (
<>
<HashRouter>
<Router />
</HashRouter>
</>
)
}
export default App
React-Router v6路由配置
react-router-dom已经升级到了v6,使用语法上有些不同,大家需要多注意。
/**
* react路由配置管理 by YXY Q:282310962
*/
import { lazy, Suspense } from 'react'
import { useRoutes, Outlet, Navigate } from 'react-router-dom'
import { Loading } from 'react-vant'
import { authStore } from '@/store/auth'
// 引入路由页面
import Login from '@views/auth/login'
import Register from '@views/auth/register'
const Index = lazy(() => import('@views/index'))
const Contact = lazy(() => import('@views/contact'))
const Uinfo = lazy(() => import('@views/contact/uinfo'))
const Chat = lazy(() => import('@views/chat/chat'))
const ChatInfo = lazy(() => import('@views/chat/info'))
const RedPacket = lazy(() => import('@views/chat/redpacket'))
const My = lazy(() => import('@views/my'))
const Fzone = lazy(() => import('@views/my/fzone'))
const Wallet = lazy(() => import('@views/my/wallet'))
const Setting = lazy(() => import('@views/my/setting'))
const Error = lazy(() => import('@views/404'))
// 加载提示
const SpinLoading = () => {
return (
<div className="rc__spinLoading">
<Loading size="20" color="#087ea4" vertical textColor="#999">加载中...</Loading>
</div>
)
}
// 延迟加载
const lazyload = children => {
// React 16.6 新增了<Suspense>组件,让你可以“等待”目标代码加载,并且可以直接指定一个加载的界面
// 懒加载的模式需要我们给他加上一层 Loading的提示加载组件
return <Suspense fallback={<SpinLoading />}>{children}</Suspense>
}
// 路由鉴权验证
const RouterAuth = ({ children }) => {
const authState = authStore()
return authState.isLogged ? (
children
) : (
<Navigate to="/login" replace={true} />
)
}
// 路由占位模板(类似vue中router-view)
const RouterLayout = () => {
return (
<div className="rc__container flexbox flex-col">
<Outlet />
</div>
)
}
// useRoutes集中式路由配置
export const routerConfig = [
{
path: '/',
element: lazyload(<RouterAuth><RouterLayout /></RouterAuth>),
children: [
// 首页
// { path: '/', element: <Index /> },
{ index: true, element: <Index /> },
// 通讯录模块
// { path: '/contact', element: lazyload(<Contact />) },
{ path: '/contact', element: <Contact /> },
{ path: '/uinfo', element: <Uinfo /> },
// 聊天模块
{ path: '/chat', element: <Chat /> },
{ path: '/chatinfo', element: <ChatInfo /> },
{ path: '/redpacket', element: <RedPacket /> },
// 我的模块
{ path: '/my', element: <My /> },
{ path: '/fzone', element: <Fzone /> },
{ path: '/wallet', element: <Wallet /> },
{ path: '/setting', element: <Setting /> },
// 404模块 path="*"不能省略
{ path: '*', element: <Error /> }
]
},
// 登录/注册
{ path: '/login', element: <Login /> },
{ path: '/register', element: <Register /> }
]
const Router = () => useRoutes(routerConfig)
export default Router
React状态管理Zustand4
这次使用了全新的支持React18 hooks语法的状态管理插件Zustand。
/**
* Zustand状态管理,配合persist本地持久化存储
*/
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
export const authStore = create(
persist(
(set, get) => ({
isLogged: false,
token: null,
loggedData: (data) => set({isLogged: data.isLogged, token: data.token})
}),
{
name: 'authState',
// name: 'auth-store', // name of the item in the storage (must be unique)
// storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used
}
)
)
OK,以上就是react18 hooks开发移动端聊天IM实例的一些分享。