[英]How to emit inputs on change using socket.io?
I'm working on a chat style app using React and socket.io, and I want to implement something where a client can see the input being typed by the other client in realtime. 我正在使用React和socket.io开发一个聊天风格的应用程序,我想实现一个客户端可以实时看到其他客户端正在键入的输入的东西。 I'm using onChange
on the input to update the state and emit the message at the same time, but that only sends messages one letter at a time to the server, and deletions don't work at all. 我在输入上使用onChange
来更新状态并同时发出消息,但是一次只能向服务器发送一个字母,并且删除根本不起作用。
Here's the frontend with extra code omitted: 这是前端,省略了额外的代码:
this.state = {
text: '',
name: '',
messages: []
}
componentDidMount() {
socket.on('RECIEVE_MESSAGE', function(msg) {
this.setState({
messages: [...this.state.messages, msg]
})
})
}
onInputChange(event) {
this.setState({
text: event.target.value
})
socket.emit('example_message', this.state.text);
this.setState({
messages: [...this.state.messages, this.state.text]
})
}
return (
<div>
<form type="text" onSubmit={this.handleSubmit}>
<input
type="text"
className="text-input"
id="name-input"
name="text-input"
required="required"
placeholder="text"
//used to save end result
value={this.state.text}
onChange={this.onInputChange}></input>
{/* <button className="next-btn"> NEXT </button> */}
<button onClick={this.sendSocketIO}>Send Socket.io</button>
</form>
<p>{this.state.text}</p>
<p>{this.state.messages}. </p>
</div>
)
And the backend: 和后端:
io.on('connection', client => {
console.log('Socket connected: ', client.id);
//recieves the message from the client, and then re-emits to everyone
client.on('SEND_MESSAGE', data => {
data.message = validate.blacklist(data.message, ['<','>','&','"','/']);
io.emit('RECEIVE_MESSAGE', data);
});
I'd like to render to the DOM a live feed of what the other client is typing, and update it with every character and character deletion. 我想向DOM提供另一个客户端正在输入的内容的实时供稿,并用每个字符和字符删除对其进行更新。
You are emitting with: 您正在发射:
socket.emit('example_message', this.state.text)
and handling with: 和处理:
client.on('SEND_MESSAGE', data...
Use the same name for the message to emit and then handle on the server. 使用相同的名称来发出消息,然后在服务器上进行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.