如何实现从 FlatList 中删除项目的方法? [英] How to implement a way to delete an item from a FlatList?

查看:58
本文介绍了如何实现从 FlatList 中删除项目的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何在 FlatList 中添加删除功能.我知道我可以制作不同的组件,但我想知道如何在这个文件中做到这一点.我已经尝试了几个小时来解决这个问题,但不知道该怎么做.

I am not sure how to add a delete function in a FlatList. I know I can make different components, but I want to know how to do it within this one file. I've trying to figure this out for hours, but do not know how to do.

export default function test() {
  const [enteredGoal, setEnteredGoal] = useState(""); 
  const [courseGoals, setCourseGoals] = useState([]); 


  const goalInput = enteredText => {
    setEnteredGoal(enteredText); 
  };

  const addGoal = () => {
    setCourseGoals(currentGoals => [
      ...currentGoals,
      { key: Math.random().toString(), value: enteredGoal }
    ]);

  };

  const removeGoal = goalId => {
    setCourseGoals(currentGoals => {
      return currentGoals.filter((goal) => goal.id !== goalId);
    })
  }

  return (
    <View style={styles.container}>
      <View>
        <TextInput
          color="lime"
          style={styles.placeholderStyle}
          placeholder="Type here"
          placeholderTextColor="lime"
          onChangeText={goalInput} 
          value={enteredGoal} 

        />
      </View>
      <FlatList
        data={courseGoals} 
        renderItem={itemData => (
          <View style={styles.listItem} >
            <Text style={{ color: "lime" }}>{itemData.item.value}</Text>
          </View>
        )}
      />
      <View>
        <TouchableOpacity>
          <Text style={styles.button} onPress={addGoal}>
            Add
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

推荐答案

你只需要稍微修改你的代码来处理删除按钮.由于您已经具有删除功能,因此请在单击删除按钮时调用该功能.就是这样.

You just need to modify your code a bit to handle the delete button. Since you already have delete functionality, call that function when you click the delete button. That's it.

<FlatList
  data={courseGoals}
  renderItem={itemData => (
    <View style={{ flexDirection: "row", justifyContent: "space-between" }}>
      <Text style={{ color: "lime" }}>{itemData.item.value}</Text>
      <TouchableOpacity onPress={() => removeGoal(itemData.item.key)}>
        <Text>Delete</Text>
      </TouchableOpacity>
    </View>
  )}
/>;

编辑
改变你的 removeGoal 函数如下

const removeGoal = goalId => {
  setCourseGoals(courseGoals => {
    return courseGoals.filter(goal => goal.key !== goalId);
  });
};

希望对你有帮助.如有疑问,请随意.

Hope this helps you. Feel free for doubts.

这篇关于如何实现从 FlatList 中删除项目的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆