Reputation: 111
I am creating an App using React-Native
.
I want to display what the user entered in the alert
.
This is to notify that the content entered by the user has been saved in the system.
How can I get the alert to display this.state.text
in the code below?
import React, {Component} from 'react';
import {Alert, Button, Text, TextInput, View} from 'react-native';
export default class Text extends Component{
state = {
text: ""
};
handleTextChange = text =>{
this.setState({text});
};
handleButtonPress(){
Alert.alert(
'保存しました!!',
//I want to appear this.state.text here
);
};
render() {
return (
<View>
<Text>URL: {this.state.text}</Text>
<TextInput placeholder='Textを入力してください' onChangeText={this.handleTextChange} value={this.state.text} />
<Button title='保存する' onPress={this.handleButtonPress}/>
</View>
);
}
}
Please lend me your strength.
Thank you.
Upvotes: 0
Views: 414
Reputation: 978
2 ways you can achieve this,
1. Use an arrow function
handleButtonPress = () => {
Alert.alert(
'保存しました!!',
this.state.text
);
};
2. Bind your (non-arrow) function, you just have to do either 1 of the following choices
//choice 1: Bind on constructor
constructor(props) {
super(props);
this.handleButtonPress = this.handleButtonPress.bind(this)
}
handleButtonPress(){
Alert.alert(
'保存しました!!',
this.state.text
);
};
render() {
return (
<View>
<Text>URL: {this.state.text}</Text>
<TextInput placeholder='Textを入力してください' onChangeText={this.handleTextChange} value={this.state.text} />
//Choice 2: Bind it everytime you call the function
<Button title='保存する' onPress={this.handleButtonPress.bind(this)}/>
</View>
);
}
Upvotes: 1
Reputation: 342
Do change like below:
import React, {Component} from 'react';
import {Alert, Button, Text, TextInput, View} from 'react-native';
export default class Text extends Component{
state = {
text: ""
};
handleTextChange = text =>{
this.setState({text:text}); //////change here
};
handleButtonPress(){
Alert.alert(this.state.text); ////////////show text from state
};
render() {
return (
<View>
<Text>URL: {this.state.text}</Text>
<TextInput placeholder='Textを入力してください' onChangeText={this.handleTextChange} value={this.state.text} />
<Button title='保存する' onPress={this.handleButtonPress}/>
</View>
);
}
}
Upvotes: 0