【发布时间】:2021-02-02 06:29:36
【问题描述】:
This is my app.js
我的应用程序的主体。 ... 导入反应,{ useState } 从“反应”; 进口 { 样式表, 文本, 看法, 按钮, 文本输入, 平面列表, } 来自“反应原生”; 从“./components/GoalItem”导入 GoalItem; 从“./components/GoalInput”导入GoalInput;
export default function App() {
const [lifeGoals, setLifeGoals] = useState([]);
const addGoalHandler = (goalTitle) => {
setLifeGoals((currentGoals) => [
...currentGoals,
{ key: Math.random().toString(), value: goalTitle },
]);
};
const removeGoalHandler = (goalId) => {
setLifeGoals((currentGoals) => {
return currentGoals.filter((goal) => goal.id !== goalId);
});
};
return (
<View style={styles.Screen}>
<GoalInput onAddGoal={addGoalHandler} />
<FlatList
keyExtractor={(item, index) => item.id}
data={lifeGoals}
renderItem={(itemData) => (
<GoalItem
id={itemData.item.id}
onDelete={removeGoalHandler}
title={itemData.item.value}
/>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
Screen: {
padding: 50,
},
});
...
This is my GoalItem which houses my list
...
import React from "react";
import { StyleSheet, View, Text, TouchableOpacity } from "react-native";
const GoalItem = (props) => {
return (
<TouchableOpacity onPress={props.onDelete.bind(this, props.id)}>
<View style={styles.ListItem}>
<Text>{props.title}</Text>
</View>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
ListItem: {
padding: 10,
marginVertical: 10,
backgroundColor: "#CCFFFF",
borderRadius: 15,
},
});
export default GoalItem;
...
This is my GoalInput which handles the userinput and appending onto the list
...
import React, { useState } from "react";
import { View, TextInput, Button, Stylesheet, StyleSheet } from "react-native";
const GoalInput = (props) => {
const [enteredGoal, setEnteredGoal] = useState("");
const InputGoalHandler = (enteredText) => {
setEnteredGoal(enteredText);
};
return (
<View style={styles.inputContainer}>
<TextInput
placeholder="Enter Task Here"
style={styles.InputBox}
onChangeText={InputGoalHandler}
value={enteredGoal}
/>
<Button title="add" onPress={props.onAddGoal.bind(this, enteredGoal)} />
</View>
);
};
const styles = StyleSheet.create({
InputBox: {
borderColor: "black",
borderWidth: 0,
padding: 10,
width: "80%",
},
inputContainer: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
},
});
export default GoalInput;
... 我相信关键可能是问题,但我真的不确定。应该发生的是,当您单击列表中的某个项目时,它应该被删除,但是它正在删除我的整个列表。我该如何解决这个问题?
【问题讨论】:
-
尝试拼接而不是过滤看看w3schools.com/js/js_array_methods.asp。过滤器只返回那些匹配大小写的元素。在您上面的代码中,您正在设置过滤产品,以防给您选择(比如说已删除)项目
标签: javascript react-native expo