我正在创建一个 ReactJS 聊天应用程序。如果用户开始输入消息,那么我希望另一个用户应该收到一条消息,说明用户名正在输入。因此,为此我使用 onChange,但用户输入的任何内容都不会出现在输入文本框中。
Message.js 文件
const socket = io('localhost:9000');
class Message extends Component {
constructor(props) {
super(props);
this.state = {
data: "",
messages: "",
typing: "",
}
this.sendMessage = this.sendMessage.bind(this);
this.onTyping = this.onTyping.bind(this);
}
sendMessage(message) {
console.log(this.state.data, "=============>state dataa")
const data = {
message,
senderId: this.props.userId,
roomId: this.state.data.roomId
};
console.log('Inside New message', data);
socket.emit('new message', data );
}
onTyping(typing) {
console.log(this.state.typing, "=====Typing Message====");
}
render() {
const { messages, userId, chatDetails } = this.props;
console.log('Chat in container : ', messages.toJS());
return (
<div className="message">
{ !chatDetails && <h1 style={{ textAlign: 'center' }}>Initiate a New Chat.</h1> }
{ chatDetails && <MessageList messages={this.state.message} user={userId} /> }
{ chatDetails && <MessageBar send={this.sendMessage} typingMessage={this.onTyping}/> }
</div>
);
}
}
const mapStateToProps = state => ({
messages: state.get('messages'),
userId: state.getIn(['profile', 'id']),
chatDetails: state.getIn(['videocall', 'callerDetails'])
});
const mapDispatchToProps = dispatch => ({
saveMessage: payload => dispatch(saveMessage(payload)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Message);
MessageBar.js
class MessageBar extends Component {
constructor(props) {
super(props);
this.state = { message: '' };
this.sendMessage = this.sendMessage.bind(this);
this.onTyping = this.onTyping.bind(this);
}
onTyping(e) {
this.setState({typing: e.target.value});
this.props.typingMessage(this.state.typing);
}
sendMessage(e) {
this.setState({message: ''});
this.props.send(this.state.message);
}
render() {
return (
<div className="message-bar">
<input
value={this.state.message}
type="text"
onChange={this.onTyping}
placeholder="Type your message ..."
/>
<button onClick={this.sendMessage}>
<i className="fa fa-paper-plane" />
</button>
</div>
);
}
}
export default MessageBar;
我在这个聊天应用程序中使用socket.io 和reactjs,有人可以帮我解决这个问题吗?
最佳答案
我认为你必须在 onTyping 函数期间更新消息的状态,而不是打字。
onTyping(e) {
this.setState({message: e.target.value});
this.props.typingMessage(this.state.typing);
}
关于javascript - 在ReactJS中添加onChange后无法在输入字段中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46051334/