javascript - 当我将函数传递给子组件时,ReactJS this.props.* 不是函数
问题描述
我写消息应用程序。当我从子组件调用传递的函数时,出现以下错误:
TypeError: this.props.createNewChat is not a function。TypeError:this.props.chooseChat不是函数。
我浏览了许多主题,尝试了我可以尝试的方法,但没有任何效果。将不胜感激任何建议,因为我是编码的初学者。
以下是我的部分代码: 父组件:
class DashboardComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
chats: [],
email: null,
selectedChat: null,
chatVisible: true
}
this.createNewChat = this.createNewChat.bind(this);
this.chooseChat = this.chooseChat.bind(this);
}
render () {
return (
<main className='dashboard-cont'>
<div className='dashboard'>
<ChatListComponent
newChat={this.createNewChat}
select={this.chooseChat}>
history={this.props.history}
chats={this.state.chats}
userEmail={this.state.email}
selectedChatIndex={this.state.selectedChat}>
</ChatListComponent>
</div>
</main>
)
}
createNewChat = () => {
this.setState({
chatVisible: true,
selectedChat: null
});
}
chooseChat = async(index) => {
await this.setState({
selectedChat: index,
chatVisible: true
});
}
子组件:
class ChatListComponent extends React.Component {
constructor(props) {
super(props);
this.select = this.select.bind(this);
this.newChat = this.newChat.bind(this);
}
render () {
if(this.props.chats.length > 0) {
return (
<main className='listOfChats'>
{
this.props.chats.map((_chat, _index) => {
return (
<div key={_index}>
<div className='chatListItem'
onClick={() => this.select(_index)}
selected={this.props.selectedChatIndex === _index}>
<div className='avatar-circle'>
<h1 className='initials'>{_chat.users.filter(_user => _user = this.props.userEmail)[1].split('')[0]}</h1>
</div>
<div className='text'>
<p id='textLine1'>{_chat.users.filter(_user => _user = this.props.userEmail)[1]}</p>
<br></br>
<p>"{_chat.messages[_chat.messages.length - 1].message.slice(0, 25)}..."</p>
</div>
</div>
</div>
)
})
}
<button className='newChatButton'
onClick={this.newChat}>
New Chat</button>
</main>
);
} else {
return (
<button className='newChatButton'
onClick={this.newChat}>
New Chat</button>
);
}
}
newChat = () => {
this.props.createNewChat();
}
select = (index) => {
this.props.chooseChat(index);
}
};
export default ChatListComponent;
解决方案
您将它们传递为newChat
和select
<ChatListComponent
newChat={this.createNewChat}
select={this.chooseChat}>
所以这些是ChatListComponent
您应该以this.props.newChat
和this.props.select
newChat = () => {
this.props.newChat();
}
select = (index) => {
this.props.select(index);
}
推荐阅读
- c - 当您在 Linux 中更改进程所有权 (uid/gid) 时,已打开的文件会发生什么情况?
- go - http.Client 和 goroutines 的不可预测的结果
- validation - Sequelize 验证 - 是否可以按属性/字段对 Sequelize 组错误进行处理?
- swift - Firebase 中的“‘StorageReference’类型的值没有成员‘数据’”
- r - R中的I型错误模拟
- p2p - 在 P2P 网络上保持统一时间
- c# - 从 TokenValidatedContext 获取控制器实例(Net Core,JwtBearerMiddleware)
- css - css3 flex:如何创建 2 列:100% + 固定宽度?
- javascript - Express.JS API 与 Node.JS 应用程序问题
- javascript - JavaScript switch 语句未执行案例 1