【问题标题】:can not use delete functionality in flatlist renderItem不能在 flatlist renderItem 中使用删除功能
【发布时间】:2019-06-02 18:10:32
【问题描述】:

删除功能在 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 is not a function 的原因。

【问题讨论】:

    标签: react-native react-native-flatlist setstate


    【解决方案1】:

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

    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>
      );
    }
    

    【讨论】:

    • 是的...谢谢,它的工作,但我不明白为什么我需要绑定renderItems?当我已经绑定 handleDelete
    • 是的...谢谢,它的工作,但我不明白为什么我需要绑定 renderItems?当我已经绑定handleDelete this 里面renderItems 指的是不同的东西,你需要绑定它来给它类上下文。
    • 您也确实将它绑定到handleDelete,但您不是在handleDelete 内部调用this,而是在renderItems 内部调用。
    • @JuniusL。我认为你需要说三遍,也许PO可能会考虑接受你的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    相关资源
    最近更新 更多