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);
}
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}
onClose={this.onClose}
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 = ()=>{
}