以下是一个示例解决方案,用于演示如何绑定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上下文。