React Native点击按钮触发if-else分数校验时报找不到变量如何解决
分数判断功能修复方案
存在的问题
- 作用域错误:你单独定义的
ComponentAction类的静态方法,无法访问AppTextInput组件内部声明的score、setScore变量,这就是触发变量找不到报错的核心原因 - 逻辑错误:判断条件中错误使用了状态更新函数
setScore和50做比较,实际应该用存储分数的状态变量score - 类型问题:
TextInput返回的输入内容是字符串类型,直接和数字比较会存在隐性类型转换风险,需要先转为数字再判断
修复后的完整代码
import React, {useState} from 'react'; import { Text, View, TextInput, Button, StyleSheet, Alert, } from 'react-native'; const styles = StyleSheet.create({ input: { height: 40, margin: 12, borderWidth: 1, padding: 10, }, }); const AppTextInput = () => { const [score, setScore] = useState(''); // 把点击判断逻辑放到组件内部,可直接访问组件状态 const onPressButton = () => { // 把字符串分数转为数字 const scoreNum = Number(score); // 先校验输入是否为有效数字 if (isNaN(scoreNum) || scoreNum < 0 || scoreNum > 100) { Alert.alert('请输入0-100之间的有效分数'); return; } if (scoreNum < 50) { Alert.alert('Sorry! You failed the test'); } else { Alert.alert('Congrats! You passed the test'); } } return ( <View> <Text>Score</Text> <TextInput placeholder="Input your score here" keyboardType="numeric" value={score} style={styles.input} onChangeText={score => setScore(score)} /> <Button title="Submit" onPress={onPressButton} /> </View> ); }; export default AppTextInput;
核心修改说明
- 移除了独立的
ComponentAction类,把点击提交的判断逻辑直接放到组件内部,确保可以正常访问组件内的状态变量 - 增加了输入有效性校验,避免用户输入非数字、超出分数范围的异常内容
- 修正了判断逻辑,将输入的字符串分数转为数字后再和及格线50做比较
内容的提问来源于stack exchange,提问作者PEKZJr
相关产品推荐
相关产品推荐

