React JS中Button的onPress无法触发函数问题求助
React按钮点击无反应问题修复
1. 按钮 onPress 未正确触发函数
你的按钮 onPress 写法仅返回了函数引用,并未执行函数;且你的函数是用const声明的函数组件写法,不应使用this(this仅适用于类组件的方法)。
错误写法:
<BlueButton onPress={()=> this.addToBlue } />
修复后写法:
// 方式1:箭头函数调用函数 <BlueButton onPress={() => addToBlue()} /> // 方式2:直接传递函数引用(更简洁) <BlueButton onPress={addToBlue} />
2. 函数嵌套语法错误,导致addToBlue无法被外部访问
你的代码中saveFavoriteRecipe函数未闭合大括号就嵌套定义了getFavoriteRecipes和addToBlue,导致这两个函数仅存在于saveFavoriteRecipe内部,外部按钮无法调用。同时addToBlue末尾多了冗余闭合大括号,属于语法错误。
错误结构:
const saveFavoriteRecipe = async () => { try { // ...业务代码 } catch (error) { // ...错误处理 } // 错误:在saveFavoriteRecipe内部嵌套定义其他函数 const getFavoriteRecipes = async () => { /* ... */ }; const addToBlue = () => { /* ... */ }; }; // 此大括号闭合后,内部函数无法被外部访问
修复后结构(所有函数处于同一层级):
const saveFavoriteRecipe = async (newItem) => { try { const value = await AsyncStorage.getItem("favoriteBlue"); const existingBlue = value ? JSON.parse(value) : []; const updatedBlue = [...existingBlue, newItem]; await AsyncStorage.setItem( "favoriteBlue", JSON.stringify(updatedBlue) ); console.log("Blue added to Bluefavourites:", newItem); } catch (error) { console.log("Error saving Bluefavorite :", error); } }; // 先闭合saveFavoriteRecipe函数 const getFavoriteRecipes = async () => { try { const serializedBlue = await AsyncStorage.getItem('favoriteBlue'); if (serializedBlue !== null) { return JSON.parse(serializedBlue); } return []; } catch (error) { console.log('Error retrieving Bluefavorite Blue:', error); return []; } }; const addToBlue = () => { if (blueData) { console.warn("updatiiiiing"); const updatedBlue = [...favoriteBlue, blueData]; setFavoriteBlue(updatedBlue); saveFavoriteRecipe(blueData); console.warn(updatedBlue); } };
3. 其他细节错误修复
- 变量名大小写不一致:
addToBlue中判断条件用blueData,但拼接时误用BlueData,统一改为小写blueData - 函数名不匹配:
addToBlue中调用的saveFavoriteBlue不存在,实际函数名为saveFavoriteRecipe,同时给saveFavoriteRecipe新增参数newItem,替换原代码中未定义的item变量
内容的提问来源于stack exchange,提问作者momonosuke
相关产品推荐
相关产品推荐

