React Native:如何为Pressable的onPress传递参数?含替代方案
解决方法
有两种简单的方式可以实现把遍历得到的answer传递给handleButtonClick函数,完成答案对比:
方法一:箭头函数包裹 onPress 回调
直接在onPress里用箭头函数调用handleButtonClick并传入当前的answer,同时修改函数接收这个参数:
修改后的渲染代码
<View> {answers.map(answer => ( <View key={answer}> <Pressable onPress={() => handleButtonClick(answer)} > <Text> {answer} </Text> </Pressable> </View> ))} </View>
修改后的handleButtonClick函数
const handleButtonClick = (selectedAnswer) => { // 对比选中答案与正确答案 const correct = questions[number].correct_answer === selectedAnswer; console.log("isCorrect = ", correct) // 答对则加分 if (correct) { setScore(prev => prev + 1); } };
方法二:用 bind 绑定参数(可选)
也可以借助bind方法给函数提前绑定参数,函数部分和方法一一致:
渲染代码修改
<Pressable onPress={handleButtonClick.bind(null, answer)} > <Text> {answer} </Text> </Pressable>
这两种方式都能顺利将循环中的answer传递到处理函数中,完成答案校验逻辑。
内容的提问来源于stack exchange,提问作者Anthon Santhez
相关产品推荐
相关产品推荐

