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套接字實例發送消息呢?文件不是很清楚。 –