当我添加新文本并按 editGoal 文件中的文本输入(使用 onBlur)外部时,我需要帮助来了解如何更新单个对象的文本值,现在,当我尝试时,文本只是“弹回”回来在里面写:
上下文文件
export const GoalsListContext = createContext()
const GoalsListContextProvider = ({children}) => {
const [goals, setGoals] = useState([{text: 'Clean the house', id:'1'}, {text: 'Wash dishes', id:'2'}])
const [selectedGoal, setSelectedGoal] = useState(null)
const addGoal = (goal) => {
setGoals([...goals, {text: goal, id:`${Math.random()}`}])
}
const focusGoal = (goal) =>{
setSelectedGoal(goal)
}
const removeGoal = (id) =>{
setGoals(goals.filter((goal)=>{
return goal.id !== id
}))
}
const updateGoal = (value) =>{
console.log(value)
}
return(
<GoalsListContext.Provider value={{goals, addGoal, focusGoal, selectedGoal, removeGoal, updateGoal}}>
{children}
</GoalsListContext.Provider>
)
}
export default GoalsListContextProvider
editGoal.js
export default EditGoal = ({navigation}) => {
const {selectedGoal, removeGoal, updateGoal} = useContext(GoalsListContext)
const handleDelete = () =>{
removeGoal(selectedGoal.id)
navigation.goBack()
}
const handleUpdateGoal = (v) => {
updateGoal(v)
}
return(
<View style={styles.mainContainer}>
<TouchableOpacity style={styles.trashContainer} onPress={handleDelete}>
<FontAwesome name="trash" size={40} color="white"/>
</TouchableOpacity>
<View style={styles.firstContainer}>
<TextInput
style={styles.goalTitle}
value={selectedGoal.text}
onChangeText={(text)=>{handleUpdateGoal(text)}}
onBlur={()=>{}} (THIS IS HOW I WANT TO UPDATE THE STATE)
/>
<Text style={styles.percentageTitle}>0% Complete</Text>
</View>
<View style={styles.secondContainer}>
<Text style={styles.todoTitle}>My todos</Text>
</View>
</View>
)
}
不知道是否需要这个,但这里还有 home.js
export default Home = ({navigation}) => {
const {goals, focusGoal} = useContext(GoalsListContext)
const handleSettingPress = (goalId) => {
const clickedGoal = goals.filter
(goal => goal.id === goalId)[0]
focusGoal(clickedGoal)
navigation.navigate("EditGoal")
}
return(
<SafeAreaView style={styles.container}>
<FontAwesome name="plus-circle" size={60} color="black" onPress={()=>navigation.navigate("AddGoal")} />
{goals.length ? (
<FlatList
data={goals}
keyExtractor={(goal)=>goal.id}
renderItem={({item})=> {
return <View style={styles.goalContainer}>
<Text style={styles.goalContainerText}>{item.text}</Text>
<TouchableOpacity onPress={() => {handleSettingPress(item.id)}}>
<FontAwesome name="edit" size={35} color="white" />
</TouchableOpacity>
</View>
}}
/>)
: (<Text style={styles.extraText}>Add a goal!</Text>)}
</SafeAreaView>
)
}
最佳答案
基本上,您希望包含一种更新 selectedGoal 变量的方法,因为这是传递给 TextInput
的值。
所以你的 updateGoal 函数必须是这样的:
const handleUpdateGoal = (value) => {
focusGoal({...selectedGoal, text: value})
}
我将 focusGoal
确定为更改 selectedGoal
的方法,因为这正是该函数在上下文文件中的用途。
关于react-native - 从文本输入编辑和更新对象文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70682809/