React Native计算器点击数字按钮显示undefined问题求助
React Native计算器点击数字显示undefined问题解决
问题描述
我是React Native新手,跟着YouTube教程制作计算器应用。教程案例点击数字能正常显示,但我的应用点击数字按钮后,结果区域和控制台均显示undefined。
我将text作为参数传递给buttonPressed函数,预期console.log(text)输出对应数字,且resultText会累加点击的数字,但实际未达预期。
相关代码
constructor() { super(); this.state = { resultText: "" } } buttonPressed(text) { console.log(text) this.setState({ resultText: this.state.resultText + text }) } render() { let rows = [] let nums = [[1,2,3], [4,5,6], [7,8,9], ['.',0,'=']] for(let i=0; i<4; i++) { let row= [] for(j=0; j<3; j++) { row.push(<TouchableOpacity onPress={() => this.buttonPressed(nums[i][j])} style={styles.btn}> <Text style={styles.txt}>{nums[i][j]}</Text> </TouchableOpacity>) } rows.push(<View style={styles.row}>{row}</View>) } let operations = ['D','+', '-', '*', '/'] let ops = [] for(let i=0; i<4; i++) { ops.push(<TouchableOpacity style={styles.btn}> <Text style={styles.txt}>{operations[i]}</Text> </TouchableOpacity>) } return ( <View style={styles.Container}> <View style={styles.result}> <Text style={styles.resultText}>{this.state.resultText}</Text> </View> <View style={styles.calculations}> <Text style={styles.txt}>121</Text> </View> <View style={styles.buttons}> <View style={styles.numbers}> {rows} </View> <View style={styles.operations}> {ops} </View> </View> </View> ); } }
问题原因及解决方法
1. this指向错误
buttonPressed函数未绑定组件实例的this,导致函数内部的this不是当前组件实例,访问this.state会得到undefined,最终拼接后resultText变成undefined+数字,显示undefined。
解决方法二选一:
- 在构造函数中绑定
this:constructor() { super(); this.state = { resultText: "" }; // 绑定this到buttonPressed函数 this.buttonPressed = this.buttonPressed.bind(this); } - 使用箭头函数定义
buttonPressed(自动绑定当前组件的this):buttonPressed = (text) => { console.log(text); this.setState({ resultText: this.state.resultText + text }); };
2. 循环变量未声明let
内层循环的j没有用let声明,会成为全局变量,可能导致循环逻辑异常(虽不是直接导致undefined的原因,但属于代码规范问题),修正为:
for(let j=0; j<3; j++) { // ... 原有代码 }
内容的提问来源于stack exchange,提问作者Kashi S
相关产品推荐
相关产品推荐

