我有以下代码
chat.js
import React from 'react';
import '../styles/Chat.css';
import Web from '../services/Web';
class Chat extends React.Component {
constructor(props) {
super(props);
this.state = {
msg:''
};
this.sendMessage = this.sendMessage.bind(this);
}
sendMessage () {
this.props.updatecommentText(this.refs.newText.value, this.props.index);
this.setState({ msg: '' });
}
render() {
return (
<div className="Chat-container">
<div className="Chat-row">
<div className="Chat-column">
<div className="Chat-card">
<div className="Chat-body">
<div className="Chat-title">React Based Chatbot</div>
<div className="Chat-messages">
{ this.props.children }
</div>
</div>
<div className="Chat-footer">
<textarea className="Chat-input" ref="newText"></textarea>
<button className="Chat-submit" onClick={this.sendMessage} defaultValue={ this.props.children }>Send</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Chat;
Web.js
import React, { Component } from 'react';
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
import Chat from '../components/Chat';
class Web extends React.Component {
constructor(props){
super(props);
this.state = {
messages:["Hi, How can I help you ?"
]
};
this.sendtobot = this.sendtobot.bind(this);
}
sendtobot(newText, i){
var arr = this.state.messages
arr.push(newText)
this.setState({messages: arr})
}
eachMessage(message, i){
return (<Chat key={i} index={i} updatecommentText={ this.sendtobot.bind(this) }>{ message }</Chat>);
}
render(){
return(
<div>
{this.state.messages.map(this.eachMessage.bind(this))}
</div>
)
}
}
export default Web;
我想从 Chat.js 中获取输入,并将其发送到 Web.js ,然后将该值推送到数组消息中,然后再次在{strong> Chat.js
中的this.props.children
但是,在运行代码时,出现错误this.props.updatecommentText is not a function.
有人可以帮我吗?
答案 0 :(得分:3)
您两次绑定this.sendtobot
。它应该只在构造函数中。
像这样
eachMessage(message, i) {
return (
<Chat
key={i}
index={i}
updatecommentText={this.sendtobot}
>
{ message }
</Chat>
);
}
答案 1 :(得分:0)
您的代码似乎有效。 Here是包含您的代码的沙箱。
我不确定它是否可以正常工作,但是没有错误。
答案 2 :(得分:0)
通过更改Web组件中的这3个功能,它开始看起来像只有一个文本区域的聊天
sendtobot(newText, i) {
this.setState({ messages: [...this.state.messages, newText] })
}
eachMessage(message, i) {
return (<p>{message}</p>);
}
render() {
return (
<div>
{this.state.messages.map(this.eachMessage.bind(this))}
<Chat updatecommentText={this.sendtobot}/>
</div>
)
}
答案 3 :(得分:-1)
您还可以将redux用作全局状态,将子组件的状态传递给父组件。