我想使用Facebook的建议发送和接收数据 https://facebook.github.io/react-native/docs/network.html#websocket 但是当我运行代码时,它无法导入" WebSocket"和应用程序 崩溃。 render方法中的代码运行得很好,但我不想这样做 一次又一次地渲染视图只是为了发送数据。 我希望componentWillMount函数中的代码能够运行以发送和 接收数据。请帮我。我会感激你的。
import React, { Component } from 'react';
import WS from 'react-native-websocket';
import { View } from 'react-native';
export default class Example extends Component {
componentWillMount() {
const ws = new WebSocket('ws://host.com/path');
ws.onopen = () => {
// connection opened
ws.send('something'); // send a message
};
ws.onmessage = (e) => {
// a message was received
console.log(e.data);
};
ws.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};
}
render() {
return (
<View style={{ flex: 1 }}>
<WS
ref={ref => { this.ws = ref }}
url="http://34.206.187.250:1880/ws/praduman"
onOpen={() => {
console.log('Open!')
this.ws.send('Hello')
}}
onMessage={console.log}
onError={console.log}
onClose={console.log}
reconnect
/>
</View>
)
}
}
答案 0 :(得分:0)
试试这个:
import React, { Component } from 'react'
import { AppRegistry, View } from 'react-native'
import WS from 'react-native-websocket'
export default class Example extends Component {
_onOpen() {
console.log('Open!')
this.ws.send('Hello')
}
_onMessage(event) {
console.log('Data',event)
}
_onError(error) {
console.log('Error',error)
}
_onClose() {
console.log('Close!')
}
render () {
return (
<View style={{flex: 1}}>
<WS
ref={ref => {this.ws = ref}}
url="wss://echo.websocket.org/"
onOpen={() => this._onOpen.bind(this)}
onMessage={(event) => this._onMessage.bind(this)}
onError={(error) => this._onError.bind(this)}
onClose={() => this._onClose.bind(this)}
/>
</View>
)
}
}