nodejs和react实现即时通讯简易聊天室功能(2)

import React from 'react'; import './socket-demo.css'; import {connect} from 'react-redux' import {setUserName} from '../redux/user.redux' @connect( null, {setUserName} ) class Login extends React.Component{ constructor(props) { super(props); this.state={ user:'' } this.login=this.login.bind(this) this.onKeyDown=this.onKeyDown.bind(this) } //键盘点击跳转 onKeyDown(e){ switch (e.keyCode) { case 13: this.login(); return; default: return; } } //添加键盘事件 componentDidMount() { document.addEventListener("keydown", this.onKeyDown) } //赋值state handleChange(title,target){ this.setState({ [title]:target.target.value }) } //赋值并跳转到聊天室页面 login(){ let {user}=this.state; if(user!==null && user.trim()!==''){ this.props.setUserName(user); this.props.history.push('/talk') } } render() { return ( <div className='loginDiv'> <input type='text' placeholder='输入昵称' onChange={v=>this.handleChange('user',v)} /> <button onClick={this.login}>进入聊天室</button> </div> ); } } export default Login

下面是重头戏,聊天室的前端展示的核心代码 打开src/iosocket-demo.js文件

import React from 'react' import io from 'socket.io-client' import {connect} from 'react-redux' import './socket-demo.css' const url='ws://localhost:9093' const socket = io(url); @connect( state=>state, {} ) class SocketDemo extends React.Component{ constructor(props) { super(props); this.state={ message:'', user:this.props.User.user, messages:[] } this.send=this.send.bind(this) this.login=this.login.bind(this) this.onKeyDown=this.onKeyDown.bind(this) } componentDidMount() { //输入欢迎信息 this.login() //增加回车事件 document.addEventListener("keydown", this.onKeyDown) //socket.io连接后台 io(url).on('connect', ()=>{ console.log('connect'); socket.on('messages', data => { //返回用户列表 this.setState({ messages:[...this.state.messages,data] }) if(this.refs.showDiv){ this.refs.showDiv.scrollTop=2000 } }); }); } componentWillUnmount() { //断开socket io连接 io('ws://localhost:9093').on('disconnect', function(){ console.log('disconntect'); }); document.removeEventListener("keydown", this.onKeyDown) } //鼠标回车事件 onKeyDown(e){ switch (e.keyCode) { case 13: this.send(); return; default: return; } } //向后台发送信息 send(){ let {user,message}=this.state; console.log(this.refs.showDiv); socket.emit('messages', {user,message}); this.setState({ message:'' }) } login(){ let user=this.props.User.user; const obj={user:'作者',message:`欢迎${user}来到聊天室`} if(user.trim()!==''){ this.setState({ user:user, messages:[obj] }) } } //赋值state handleChange(title,target){ this.setState({ [title]:target.target.value }) } render() { let cn='showInfo' return ( <div> <div className='talkDiv'> <div className='operatingDiv'> <input type='text' placeholder='请在此输入聊天信息' onChange={v=>this.handleChange('message',v)} value={this.state.message} /> <button onClick={this.send}>发送链接</button> </div> <div ref='showDiv' className='showDiv'> { this.state.messages.map((v,index)=>{ if(index===0){ cn='titleInfo' }else{ cn='showInfo' } return ( <div className={cn} key={index}> <span>{v.user}:</span> <span>{v.message}</span> </div> ) }) } </div> </div> </div> ); } } export default SocketDemo;

最后加上src/iosocket-demo.css

body{ background: #008DB7; font-family: 'Microsoft YaHei UI'; } .loginDiv{ text-align: center; margin: 150px auto 0; width: 250px; } .loginDiv input[type='text']{ display: inline-block; box-sizing: border-box; border-radius: 5px; padding-left: 5px; border: none; width: 250px; height: 35px; line-height: 35px; } .loginDiv button{ display: inline-block; box-sizing: border-box; border-radius: 5px; padding-left: 5px; border: none; width: 250px; height: 35px; line-height: 35px; margin-top: 10px; background: #0067A2; color: #ffffff; } .talkDiv{ position: fixed; top: 0; left: 0; right: 0; bottom: 0; } .talkDiv .operatingDiv{ position: fixed; bottom: 0; left: 0; right: 0; height: 40px; display: flex; } .talkDiv .operatingDiv input[type='text']{ flex: 1; height: 40px; line-height: 40px; box-sizing: border-box; padding-left: 10px; } .talkDiv .operatingDiv button{ display: inline-block; box-sizing: border-box; border-radius: 5px; border: none; width: 250px; height: 40px; line-height: 40px; background: #0067A2; color: #ffffff; } .talkDiv .showDiv{ position: fixed; bottom: 40px; left: 0; right: 0; top: 0; font-size: 16px; color: #ffffff; overflow: auto; } .talkDiv .showDiv .titleInfo{ padding: 10px; color: yellow; font-size: 20px; } .talkDiv .showDiv .showInfo{ padding: 10px; }

在package.json中加入命令行

"scripts": { "start": "node scripts/start.js", "build": "node scripts/build.js", "server": "nodemon server/index.js" },

运行后台 yarn server

运行前台 yarn start

启动程序

总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/6f10126f98403b56c5519b300682b208.html