不能在 flatlist renderItem 中使用删除功能

can not use delete functionality in flatlist renderItem

删除功能在 flatlist renderItem 方法中不起作用,但如果我使用 map 函数而不是 flatlsit 来呈现数据,它将工作得很好。

这里是示例代码

class App extends Component {
  state = {
    todos: [
      { todo: 'go to gym', id: 1 },
      { todo: 'buy a mouse', id: 2 },
      { todo: 'practice hash table', id: 3 },
      { todo: 'iron clothes', id: 4 }
    ]
  };

  keyExtractor = item => item.id.toString();

  handleDelete = id => {
    const todos = this.state.todos.filter(item => item.id !== id);
    this.setState({ todos });
  };

  renderItems({ item }) {
    return (
      <View
        style={{
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between'
        }}
      >
        <Text style={{ fontSize: 16 }}>{item.todo}</Text>
        <TouchableOpacity
          onPress={() => this.handleDelete(item.id)}
          style={{ marginRight: 15 }}
        >
          <Text style={{ color: 'red' }}>Delete</Text>
        </TouchableOpacity>
      </View>
    );
  }

  render() {
    return (
      <View>
        {/* {this.renderItems()} */}
        <FlatList
          data={this.state.todos}
          keyExtractor={this.keyExtractor}
          renderItem={this.renderItems}
        />
      </View>
    );
  }
}

我不明白它给我错误 _this2.handleDelete 不是函数的原因。

你没有绑定你的函数,在你的构造函数中绑定函数或使用数组函数

renderItems = ({ item }) => {

  return (
    <View
      style={{
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
      }}>
      <Text style={{ fontSize: 16 }}>{item.todo}</Text>
      <TouchableOpacity
        onPress={() => this.handleDelete(item.id)}
        style={{ marginRight: 15 }}>
        <Text style={{ color: 'red' }}>Delete</Text>
      </TouchableOpacity>
    </View>
  );
}