我正在使用React-Native
创建一个应用。
我想显示用户在alert
中输入的内容。
这是为了通知用户输入的内容已保存在系统中。
如何在以下代码中显示this.state.text
警报?
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>
);
}
}
请借给我你的力量。
谢谢。
答案 0 :(得分:1)
两种实现方法,
1。使用箭头功能
handleButtonPress = () => {
Alert.alert(
'保存しました!!',
this.state.text
);
};
2。绑定(非箭头)功能,您只需执行以下任一选择即可
//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>
);
}
答案 1 :(得分:0)
进行如下更改:
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>
);
}
}