javascript - 在 React 中将函数传递给组件的新属性
问题描述
嗨,我正在尝试在 React 中尝试几个代码片段。以下代码生成“无法读取未定义的属性 'removeComment'”类型错误。我已尝试使用不同的技术将函数绑定到反应文档https://reactjs.org/docs/faq-functions.html中描述的类,但问题仍然存在。以下是我的代码:
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
comments: ["item1", "item2", "item3"]
}
this.removeComment = this.removeComment.bind(this);
this.updateComment = this.updateComment.bind(this);
}
removeComment = (i) => {
console.log("Removing comment " + i)
var arr = this.state.comments;
arr.splice(i, 1)
this.setState({ Comments: arr })
}
updateComment = (newText, i) => {
var arr = this.state.comments;
arr[i] = newText
this.setState({ comments: arr })
}
eachComment(text, i) {
return (<Comment key={i} index={i}
deleteComment={this.removeComment.bind(this)}
updateCommentText={this.updateComment.bind(this)}>{text}</Comment>)
}
render() {
return (
<div>
{
this.state.comments.map(this.eachComment)
}
</div>
)
}
}
解决方案
推荐阅读
- javascript - Puppeteer 流逻辑,检查是否发生导航(vs 等待)
- node.js - nodejs应用程序崩溃后Docker容器不会重新启动?
- java - 试图阻止用户在 java 中将字符串输入我的双精度
- error-handling - 包 pdftex.def 错误:文件;我该怎么做才能让 LATEX 显示图像?
- javascript - Winston - 显示错误堆栈跟踪对象和正常格式的消息
- angular - 在 Angular 9 中,如果导航器不在线,如何仅将缓存用于 http get 请求
- c++ - 如何简化多 switch case 语句?
- python - AttributeError:“int”对象没有属性“权重”
- unit-testing - 在 jpm test 命令中打印测试用例名称
- node.js - BrowserSync with Nodemon and Express Server