0
我对UI开发,JavaScript,ReactJS相当陌生,所以请原谅缺乏基础知识。ReactJS与使用WebSockets的服务器通信
我想开发一个简单的ReactJS应用程序,它通过表单接受用户输入,发送到后端服务器并从服务器接收响应。后端服务器正在监听WebSocket URL'ws:// localhost:8025/websockets/WSService'。我已经提供了下面的代码片段。当我输入一些文本输入并点击'提交'时,服务器已成功接收到该消息。我现在试图接收服务器发送的响应,并想知道在哪里设置'onmessage'功能。
我已经审议了以下问题,但他们对我的要求略有不同,我不能建议直接映射到我的解决方案:
- how react js acts as a websocket client?
- https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
代码片段如下:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
ws: new WebSocket('ws://localhost:8025/websockets/WSService'),
value: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
console.log(this.state.value);
}
handleSubmit(event) {
event.preventDefault();
this.state.ws.send(this.state.value);
console.log(event.target.value);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
'react-websocket'文件说你可以将它渲染为组件。 –
@Prakash sharma,是的,react-socket网站https://www.npmjs.com/package/react-websocket提供了一个ProductDetail代码示例,其中Websocket被用作组件:“ “,但是我该如何使用这个web套接字实例发送消息呢?文件不是很清楚。 –