Reputation: 1007
I want to be able to retrieve the value of the text after the user presses enter/return.
I tried the following ...
class HomePage extends Component {
constructor(props) {
super(props);
this.state = {
text:''
}
}
callTextSubmit = (val) => {
console.log('callTextSubmit ', val);
};
render() {
return (
<View>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.setState({ text })}
onSubmitEditing={(text) => this.callTextSubmit(text)}
value={this.state.text}
/>
</View>
)
}
}
This returns the following... from the console log.
Proxy {dispatchConfig: {…}, _targetInst: FiberNode, isDefaultPrevented: ƒ, isPropagationStopped: ƒ, _dispatchListeners: ƒ, …}
>[[Handler]]:Object
>[[Target]]:Class
>[[IsRevoked]]:false
I want to access the value from the text input, is there a workaround to this? Thank you
Upvotes: 1
Views: 156
Reputation: 1133
Since you are using this line to add the TextInput's value to state
onChangeText={(text) => this.setState({ text })}
The reasonable way would be to get the value from state on your onPress function on a Button (TouchableOpacity/TouchableHighlight) added to your View like this:
<TouchableOpacity onPress={()=>console.log(this.state.text)}>
<Text>
Enter
</Text>
</TouchableOpacity>
Here is code for your Component
class HomePage extends Component {
constructor(props) {
super(props);
this.state = {
text:''
}
}
callTextSubmit = () => {
console.log(console.log(this.state.text));
};
render() {
return (
<View>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.setState({ text })}
value={this.state.text}
/>
<TouchableOpacity onPress={()=>console.log(this.state.text)}>
<Text>
Enter
</Text>
</TouchableOpacity>
</View>
)
}
Upvotes: 1
Reputation: 112787
The argument for the onSubmitEditing
handler is the event, not the current input.
Since you set the state variable text
each time the TextInput
is changed, you can just use the text
variable in your state instead.
callTextSubmit = () => {
console.log('callTextSubmit ', this.state.text);
};
Upvotes: 2