我是一名初学React的人,正在创建一个聊天机器人,为每个动作返回一组按钮选择。我在服务器端使用Socket.io,在前端使用React。希望每个按钮都有一个OnClick函数,但是我无法实现。
以下是服务器返回的数据格式:
然而,当渲染此组件时,我看到了这个错误 -
无法读取未定义的属性“props”
这真是让我崩溃。我已经尝试了一切可能的方法。
以下是服务器返回的数据格式:
var data = {
buttonShow: true,
buttons: [
{
text: 'I DID NAAAAHT'
},
{
text: 'OH HAI MARK'
}
],
message: {
author: "Mark",
time: '12:00 PM',
message: "Did you hit Lisa?"
}
};
这是我的聊天窗口组件类
import React from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router';
import io from "socket.io-client";
class ChatWindow extends React.Component{
constructor(props){
super(props);
this.state = {
email: '',
message: '',
time: '',
buttonShow: false,
buttons: [],
messages: [],
buttonSelection: ''
}
this.socket = io('http://localhost:8080')
this.socket.on('RECEIVE_MESSAGE', function(data){
addMessage(data);
});
const addMessage = data => {
console.log(data);
this.setState({messages: [...this.state.messages, data.message]});
this.setState({buttonShow: data.buttonShow});
this.setState({buttons: data.buttons});
console.log(this.state);
//if(this.state.buttonShow==false){}
};
this.sendButtonSelection = e => {
this.setState({buttonSelection: e.target.value});
console.log(e.target.value);
};
};
render(){
return(
<div>
<div className="panel-body">
{this.state.messages.map(message => {
return(
<ul className="chat">
<li className="">
<div className="chat-body clearfix">
<div className="header">
<strong className="primary-font">{message.author}</strong> <small className="pull-right text-muted">
<span className="glyphicon glyphicon-time"></span>{message.time}</small>
</div>
<p>{message.message}</p>
</div>
</li>
</ul>
)
})}
</div>
<div class="panel-footer">
{<ChatInput myDataProp = {this.state.buttonShow} myButtonProp = {this.state.buttons} onClickProp = {this.sendButtonSelection}/>}
{}
</div>
</div>
);
}
};
class ChatInput extends React.Component {
render(){
if(this.props.myDataProp == false) {
return (
<div className="input-group">
<input id="btn-input" type="text" className="form-control input-sm" placeholder="Type your message here..." />
<span className="input-group-btn">
<button className="btn btn-warning btn-sm" id="btn-chat">
Send</button>
</span>
</div>
)
} else {
return (
<div>
{this.props.myButtonProp.map(function(item, i){
return(
<Button buttonProp = {item.text} buttonOnClick = {this.props.onClickProp}/>
)
})}
</div>
)
}
}
}
class Button extends React.Component {
render(){
return(
<div>
<button type="button" className="btn btn-default btn-round" value={this.props.buttonProp} onClick={this.props.buttonOnClick}>{this.props.buttonProp}</button>
</div>
)
}
}
module.exports = ChatWindow;