以下是一个示例解决方案,用于演示如何绑定this并调用删除项目的函数:
class TodoList extends React.Component {
constructor(props) {
super(props);
this.state = {
items: ['item1', 'item2', 'item3']
};
}
deleteItem(index) {
const items = [...this.state.items];
items.splice(index, 1);
this.setState({ items: items });
}
render() {
return (
{this.state.items.map((item, index) => (
-
{item}
))}
);
}
}
在这个示例中,我们有一个TodoList
组件,它有一个items
状态数组,存储了一些待办事项。在deleteItem
函数中,我们首先使用展开运算符创建了一个新数组items
,然后使用splice
方法删除了指定索引的项目。最后,我们使用setState
方法更新了状态。
在render
方法中,我们使用map
函数遍历items
数组,并为每个项目渲染一个li
元素。在每个li
元素中,我们添加了一个删除按钮,并使用bind
方法绑定了deleteItem
函数的this
上下文和要删除的项目的索引。这样,当点击删除按钮时,会调用deleteItem
函数,并传递对应的索引作为参数。
请注意,我们使用bind
方法来绑定this
,以确保在调用deleteItem
函数时,它具有正确的this
上下文。这是因为在map
函数中,回调函数的this
上下文默认是undefined
。通过使用bind
方法,我们将this
绑定到当前组件实例,从而确保在调用deleteItem
函数时,它具有正确的this
上下文。