TextInput的Clear方法未定义

时间:2018-03-16 11:37:33

标签: ios react-native

我刚刚开始研究ReactNative,我正在开发一个应用程序,其中包含TextInput个标题Button的{​​{1}}。我试图在按钮点击时clear textinput,但它不起作用。当我控制clear时,它将被定义为未定义。这是我的代码,

import React, { Component } from 'react';
import { View, Text, Button, AlertIOS, TextInput, StyleSheet, Image, TouchableOpacity, KeyboardAvoidingView, Keyboard } from 'react-native';

import Colors from '../res/value/Colors';
import Styles from '../res/value/Styles';

import TouchableText from '../component/TouchableText';
import TouchableImage from '../component/TouchableImage';

export default class AddViewPin extends Component{

  constructor(props) {
    super(props);

    this.state = {
      pin: ''
    }
  }

  static navigationOptions = ({navigation}) => {
    const {params} = navigation.state;
    return{
      headerRight: (
          <TouchableImage
          style = {Styles.headerButtonRight}
          source = {require('../res/image/ic_save.png')}
          onPress = {() => params.handleSave && params.handleSave()}/>
      )
    }
  }

  savePin = () => {
    if (this.state.pin == ''){
      console.log('Your thoughts can\'t be empty!');
    } else {
      console.log(this.state.pin);
      console.log(this.textInputPin.clear());
      this.textInputPin.clear();
    }
  }

  onSubmitHandler = (event) => {
    Keyboard.dismiss();
  }

  componentDidMount () {
    this.props.navigation.setParams({handleSave: () => this.savePin()});
  }

  handlePin = (text) => {
    this.setState({
      pin: text
    })
  }

  render(){
    return(
      <KeyboardAvoidingView style = {{flex: 1}} >
        <TextInput
          onChangeText = {this.handlePin}
          ref={input => { this.textInputPin = input }}
          returnKeyType = 'done'
          blurOnSubmit = {true}
          onSubmitEditing={(event) => this.onSubmitHandler(event)}
          placeholder = 'Pin your out of the box thoughts here...'
          multiline = {true}
          style = {styles.textInput} />
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({
  textInput: {
    flex: 1,
    margin: 4,
    marginLeft: 16,
    marginRight: 16
  }
});

1 个答案:

答案 0 :(得分:-1)

为textinput添加值prop。

<TextInput value= {this.state.pin} />

现在你的textinput从状态获取引脚,所以如果你想清除textInput只是用空文本setState。

this.setState({
     pin: ''
})