我遇到了一个非常简单的问题。我有带有用户名、密码和按钮的登录表单。在我的按钮处理程序中,我尝试获取 textinput 值。但总是得到未定义的值。我错过了什么吗?
render() {
<ExScreen
headerColor={this.state.headerColor}
scrollEnabled={this.state.enableScroll}
style={styles.container} >
<View >
<View >
<View style={[styles.inputContainer]} >
<TextInput
ref= "username"
onChangeText={(text) => this.setState({text})}
value={this.state.username}
/>
</View>
<Button style={{color: 'white', marginTop: 30, borderWidth: 1, borderColor: 'white', marginLeft: 20*vw, marginRight: 20*vw, height: 40, padding: 10}}
onPress={this._handlePress.bind(this)}>
Sign In
</Button>
...
_handlePress(event) {
var username=this.refs.username.value;
原文由 WayneZhao 发布,翻译遵循 CC BY-SA 4.0 许可协议
快速且优化程度较低的方法是在 onChangeText 回调中使用箭头函数,通过传递
username
作为 onChangeText 回调中的参数。然后在您的
_handlePress
方法中但这有几个缺点!!!
最佳实践是使用
handleInputChange
类的处理程序,并在构造函数中绑定 ``this`。或者,如果您使用自动绑定
this
的 es6 类属性简写。但这在测试和性能方面有缺点。 在这里阅读更多