How to implement a way to delete an item from a FlatList?

非 Y 不嫁゛ 提交于 2021-02-11 06:12:31

问题


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

回答1:


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

EDIT
change your removeGoal function as below

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

Hope this helps you. Feel free for doubts.



来源:https://stackoverflow.com/questions/59907433/how-to-implement-a-way-to-delete-an-item-from-a-flatlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!