React Native--TextInput

510 阅读1分钟

type Props = {};
export default class App extends Component<Props> {
    constructor(props){
        super(props);

        this.state = {
            inputText:"",
            inputName:""
        };
    }

    show() {
        Alert.alert("提示", this.state.inputText);
    }

    showName() {
        Alert.alert("名字", this.state.inputName);
    }

    updateText = (inputText) => this.setState({inputText});
    updateName = (inputName) => this.setState({inputName});

    render() {
      return (
          <View style={styles.flex}>
              <View style={styles.viewStyle}>
                  <TextInput style={styles.inputView} returnKeyType="search" placeholder="请输入内容" onChangeText={this.updateText}/>
                  <TouchableHighlight style={styles.searchBtn} onPress={this.show.bind(this)} underlayColor='#E1F6FF'>
                      <Text style={styles.btnFontStyle}>搜索</Text>
                  </TouchableHighlight>
              </View>

              <View style={styles.viewStyle}>
                  <TextInput style={styles.inputView} returnKeyType="search" placeholder="请输入内容" onChangeText={this.updateName}></TextInput>
                  <TouchableHighlight style={styles.searchBtn} onPress={this.showName.bind(this)} underlayColor='#E1F6FF'>
                      <Text style={styles.btnFontStyle}>名字</Text>
                  </TouchableHighlight>
              </View>
          </View>
      );
  }
}


注意坑1:

   使用TouchableHighlight时,需要关联onPress点击监听,写法样式:

 onPress={this.showName.bind(this)}

注意坑2:

    当需要获取TextInput输入框中的内容时,需要监听onChangeText方法,该方法是监听输入框中内容的改变,因为RN中的变量值存储在state中,所以在ES6中首先需要重写初始化函数constructor,在里面加入要保存输入框内容的变量名和初始值,在监听函数中,使用剪头函数传值this.setState进行更新对应的值。


最终样式图: