react-simple-websocket

react websocket组件容器
提供 onOpen,onMessage,onError,onClose等方法,
是一个轻便的websocket组件
支持重连功能

react-simple-websocket

A simple websocket component for React

Installation

1
2
$ npm install react-simple-websocket --save
$ yarn add react-simple-websocket

Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import React from 'react';
import SimpleWS from 'react-simple-websocket';

export default class Example extends React.Component {
constructor(props) {
super(props);
const that = this;

that.state = {
wsData: "",
};

that.sender = null;
}

onMessage = data => {
const that = this;

//get the data from ws
that.setState({
wsData: data
});
};

onOpen = sender => {
const that = this;
that.sender = sender;

//use sender to send your data
sender("xxxxx");
};

onClick = () => {
const that = this;

that.sender('halo,it's me!');
};

render() {
return (
<div>
<SimpleWS
url="ws://localhost:8080"
onOpen={that.onOpen}
onMessage={that.onMessage}
onClose={that.onClose}
/>
<button onClick={that.onClick}>send</button>
</div>
);
}
};

Properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
static propTypes = {
url: PropTypes.string.isRequired,
onOpen: PropTypes.func,
onMessage: PropTypes.func.isRequired,
onError: PropTypes.func,
onClose: PropTypes.func,
debug: PropTypes.bool,
reconnect: PropTypes.bool
};

static defaultProps = {
debug: false,
reconnect: true
};

License

MIT

PenZ wechat
交个朋友吧
点滴分享,您的支持将极大的鼓励我!