在React-Native的Alert上显示this.state

时间:2019-03-15 04:07:38

标签: react-native

我正在使用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:&nbsp;{this.state.text}</Text>
        <TextInput placeholder='Textを入力してください' onChangeText={this.handleTextChange} value={this.state.text} />
        <Button title='保存する' onPress={this.handleButtonPress}/>
      </View>
    );
  }
}

请借给我你的力量。
谢谢。

2 个答案:

答案 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:&nbsp;{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:&nbsp;{this.state.text}</Text>
        <TextInput placeholder='Textを入力してください' onChangeText={this.handleTextChange} value={this.state.text} />
        <Button title='保存する' onPress={this.handleButtonPress}/>
      </View>
    );
  }
}