react websocket接受消息推送

//编写ReactWebsocket组件
import React from 'react';
import Websocket from 'react-websocket';
interface ReactWebsocketProps {
    onMessage:(data:any)=>void;
    onOpen:(data:any)=>void;
    onClose:()=>void;
    url:any;
    reconnect:any;
    debug:any;
}
class ReactWebsocket extends React.Component<ReactWebsocketProps,any>{
  private refWebSocket:any;
  constructor(props: any) {
    super(props);
    console.log('props',props);
    this.handleData = this.handleData.bind(this);
    this.handleOpen = this.handleOpen.bind(this);
    this.handleClose = this.handleClose.bind(this);
  };
  handleData(data:any) {
    console.log('data',data);
    console.log('this.props',this.props)
    this.props.onMessage(data)
  }
 
  handleOpen(value:any){
      console.log('value',value)
    this.props.onOpen(value);
    // this.refWebSocket.sendMessage(value);
  }
 
  handleClose() {
    this.props.onClose()
  }
 
  sendMessage(message:any){
    this.refWebSocket.sendMessage(message);
  }
 
  render() {
    const {url,reconnect,debug} =this.props;
    return (
      <Websocket 
        url={url}
        onMessage={this.handleData}
        onOpen={this.handleOpen} 
        onClose={this.handleClose}
        reconnect={reconnect} 
        debug={debug}
        ref={(_Websocket:any) => {
          this.refWebSocket = _Websocket;
        }}/>
    );
  }
}
 
export default ReactWebsocket;

调用
 	private refWebSocket:any;
    constructor(props: any) {
        super(props);
        this.onMessage = this.onMessage.bind(this);
        this.onOpen = this.onOpen.bind(this);
        this.onClose= this.onClose.bind(this);
    };


  <ReactWebsocket 
                    url='ws://ip:端口/接口名称' 
                    onMessage={this.onMessage} //接受信息的回调
                    onOpen={this.onOpen} //websocket打开
                    onClose={this.onClose} //websocket关闭
                    reconnect={true} 
                    debug={true}
                    ref={Websocket => {
                        this.refWebSocket = Websocket;
                    }}
                />

onMessage = (data:any)=>{//接受信息
        console.log('data',data)
        this.onShowNotification(data);//消息提醒框
    }
    onShowNotification = (data:any)=>{
        notification.open({
            message: `您收到了 1 条预警消息`,
            description: (
              <Content
                onDetailCheck={()=>{}}
              />
            ),
            duration: 4.5,
          });
    }
    onOpen = (value:any)=>{
        console.log('value',value)
    }
    onClose = ()=>{
  
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值