I just started learning react native, after i learned reactJs. I was wondering how to set the value of the TextInput when the button is pressed as the state value "message", and not to have it hard coded as i have it at the moment…
export default class Writing extends Component {
constructor() {
super();
this.state={
message: "",
};
}
onSend = () => {
this.setState({ message: "Hello world!" });
alert(this.state.message)
}
render(){
return (
<View>
<TextInput
style={styles.input}
placeholder="Your message"
onChangeText={this.state.message}
/>
<Button
title="Submit"
onPress={this.onSend}
/>
</View>
)
}
}```
3
Answers
It is the same in react-native as in react. So you should do the same things i.e:
You need
value
props forTextInput
. You may refer to the document written by React Native.https://reactnative.dev/docs/textinput
You can modify your code like this.
Replace your
onSend
with the below code.onChangeText
never holds the state, it is used to change the state. So, please replace your TextInput component with the below code.