I am stuck with a very simple problem. I have login form with username, password and button. In my button handler, I try to get the textinput value. But always get undefined value. Am I missing something?
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;
The value attribute specifies the value of an <input> element. The value attribute is used differently for different input types: For "button", "reset", and "submit" - it defines the text on the button. For "text", "password", and "hidden" - it defines the initial (default) value of the input field.
The quick and less optimized way to do this is by using arrow function inside your onChangeText callback, by passing username
as your argument in your onChangeText callback.
<TextInput ref= {(el) => { this.username = el; }} onChangeText={(username) => this.setState({username})} value={this.state.username} />
then in your _handlePress
method
_handlePress(event) { let username=this.state.username; }
But this has several drawbacks!!!
Best practice is to use a handler like handleInputChange
and bind ```this`` in the constructor.
... constructor(props) { super(props); this.handleChange= this.handleChange.bind(this); } ... handleChange(event = {}) { const name = event.target && event.target.name; const value = event.target && event.target.value; this.setState([name]: value); } ... render() { ... <TextInput name="username" onChangeText={this.handleChange} value={this.state.username} /> ... } ...
Or if you are using es6 class property shorthand which autobinds this
. But this has drawbacks, when it comes to testing and performance. Read More Here
... handleChange= (event = {}) => { const name = event.target && event.target.name; const value = event.target && event.target.value; this.setState([name]: value); } ... render() { ... <TextInput name="username" onChangeText={this.handleChange} value={this.state.username} /> ... } ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With