我正在运行 this目前关于 React 的教程,我遇到了 2 个组件之间的事件问题。
这是第一个:
class TodoComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
todos: ['item 1', 'item 2', 'item 3', 'item 4']
}
}
onDelete(item) {
const updatedTodos = this.state.todos.filter((val, index) => {
return item !== val;
});
this.setState({
todos: updatedTodos
});
}
render() {
let todos = this.state.todos;
todos = todos.map((item, index) => {
return (
<TodoItem item={item} key={index} onDelete={this.onDelete}/>
);
});
return (
<div id="todo-list">
<p>The busiest people have the most leisure...</p>
<ul>{todos}</ul>
</div>
);
}
}
第二个:
class TodoItem extends React.Component {
handleDelete() {
this.props.onDelete(this.props.item);
}
render() {
return (
<li>
<div className="todo-item">
<span className="item-name">{this.props.item}</span>
<span className="item-delete" onClick={this.handleDelete}> x </span>
</div>
</li>
);
}
}
我收到这个错误:
TypeError: this is undefined
bundle.js:10896:7
webpack 包中的那一行引用了第二个模块中的以下方法...
handleDelete() {
this.props.onDelete(this.props.item);
}
很抱歉,如果这最终成为一个简单的解决方案,这对我来说是 React 的第一天。
最佳答案
当你在 React 中有事件处理程序时,你必须确保将 this
的正确值绑定(bind)到这些处理程序。
有多种方法可以做到这一点,但一种简单而常见的方法是将处理程序包裹在一个箭头函数中,它在您的处理程序中维护this
的预期值:
// TodoItem
<span className="item-delete" onClick={() => this.handleDelete()}> x </span>
// TodoComponent
<TodoItem item={item} key={index} onDelete={(item) => this.onDelete(item)}/>
这背后的原因是事件处理程序被异步调用,并且 this
的值在该上下文中未定义,除非您采取额外的预防措施以确保 this
指向预期的值。
进一步阅读 (MDN):this (请参阅讨论箭头函数的部分)
编辑:我用你的代码创建了这个 JSFiddle有一个工作示例。
关于javascript - 在 react 组件之间传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47565241/