React Native:如何在alertFunction中获取TextInput的输入值?
解决React Native中点击Submit弹出输入框内容的问题
我来帮你一步步搞定这个问题,你的代码里有几个小细节需要调整,才能让alertFunction正确获取到输入框的值:
1. 同步输入值到组件状态
你的TextInput的value绑定的是this.state.myNumber,但当前的validate函数只更新了验证相关状态,没把用户输入的文本同步到myNumber里。首先要在validate函数里补上状态更新:
validate(text, type) { const num = /^[0-9]+$/; // 补充分号,修复语法错误 // 先把输入文本同步到state的myNumber中 this.setState({ myNumber: text }); if (type == 'telephone') { if (num.test(text)) { this.setState({ telephoneValidate: true, buttonInvalid: false }); } else { this.setState({ telephoneValidate: false, buttonInvalid: true }); } } }
2. 修正alertFunction并确保this指向正确
你的alertFunction现在接收的text参数没有实际传入,而且要获取的是存在state里的myNumber。另外要注意组件方法的this绑定问题,不然会找不到this.state,这里给你两种常用的解决方式:
方式一:用箭头函数定义方法
箭头函数会自动绑定当前组件的this,不用额外处理:
alertFunction = () => { Alert.alert(this.state.myNumber); }
方式二:在构造函数中绑定this
如果你的组件是类组件,可以在构造函数里手动绑定方法的this:
constructor(props) { super(props); this.state = { myNumber: '', telephoneValidate: true, buttonInvalid: true, // 其他初始状态 }; this.alertFunction = this.alertFunction.bind(this); } alertFunction() { Alert.alert(this.state.myNumber); }
方式三:在onPress时用箭头函数调用
也可以直接在TouchableOpacity的onPress里用箭头函数调用方法,保证this指向正确:
<TouchableOpacity style={[styles.ButtonStyle, { backgroundColor: this.state.buttonInvalid ? '#607D8B' : '#009688' }]} activeOpacity={.5} disabled={this.state.buttonInvalid} onPress={() => this.alertFunction()} > <Text style={styles.TextStyle}>Submit</Text> </TouchableOpacity>
3. 确认初始状态已定义
一定要在组件初始状态里声明myNumber,比如在constructor中:
this.state = { myNumber: '', telephoneValidate: true, buttonInvalid: true, };
最终核心代码片段
整合以上修改后,关键部分的代码大概是这样的:
constructor(props) { super(props); this.state = { myNumber: '', telephoneValidate: true, buttonInvalid: true, }; } alertFunction = () => { Alert.alert(this.state.myNumber); } validate(text, type) { const num = /^[0-9]+$/; this.setState({ myNumber: text }); if (type === 'telephone') { const isValid = num.test(text); this.setState({ telephoneValidate: isValid, buttonInvalid: !isValid }); } } // 渲染部分 render() { return ( <> <TextInput style={[!this.state.telephoneValidate ? { borderWidth: 3, borderColor: 'red' } : null]} keyboardType='numeric' onChangeText={(text) => this.validate(text, 'telephone')} value={this.state.myNumber} maxLength={10} /> <TouchableOpacity style={[styles.ButtonStyle, { backgroundColor: this.state.buttonInvalid ? '#607D8B' : '#009688' }]} activeOpacity={.5} disabled={this.state.buttonInvalid} onPress={this.alertFunction} > <Text style={styles.TextStyle}>Submit</Text> </TouchableOpacity> </> ); }
这样调整后,点击Submit按钮时,alertFunction就能正确弹出输入框里的内容啦~
内容的提问来源于stack exchange,提问作者Moni C
相关产品推荐
相关产品推荐

