Подтвердить что ты не робот

Clear React Native TextInput

Работа с примером Redux AddTodo в React Native. В первом примере AddTodo ниже используется состояние для хранения значения TextInput и работает нормально.

class AddTodo extends React.Component{

    constructor(props){
        super(props);
        this.state = { todoText: "" }; 
    }
    update(e){
        if(this.state.todoText.trim()) this.props.dispatch(addTodo(this.state.todoText)); 
        this.setState({todoText: "" }); 
    }
    render(){
        return(
            <TextInput 
                value = {this.state.todoText}
                onSubmitEditing = { (e)=> { this.update(e); } }
                onChangeText = { (text) => {this.setState({todoText: text}) } } />
        );
    }
}

Однако, следуя нескольким примерам Redux, следующий код намного короче и также работает, за исключением того, что TextInput value не очищается после отправки

let AddTodo = ({ dispatch }) => {

  return (
      <TextInput 
          onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } } 
      />
  )
}

Есть ли способ очистить значение InputText от onSubmitEditing?

4b9b3361

Ответ 1

Добавьте ref в свой TextInput, например:

 <TextInput ref={input => { this.textInput = input }} />

затем вызовите this.textInput.clear(), чтобы очистить введенное значение

Ответ 2

Это даст стандартную кнопку с открытым текстом.

<TextInput clearButtonMode="always" />

Ответ 3

Я использую базу Native, и вот как я сделал это работает

constructor(props) {
    super(props);
    this.searchInput = React.createRef();
}

<Input
    placeholder="Search"
    ref={this.searchInput}
/>

тогда всякий раз, когда я хочу очистить, я использую

    this.searchInput.current._root.clear();

ссылка https://github.com/facebook/react-native/issues/18843

Ответ 4

В соответствии с изменениями и рекомендациями, появившимися после React 16.3, вам нужно будет получить ссылку в вашем конструкторе, используя React.createRef:

В функции конструктора: this.myTextInput = React.createRef();

При рендере функция:

<TextInput ref={this.myTextInput}/>

И тогда вы можете позвонить

this.myTextInput.current.clear();

[1] https://reactjs.org/docs/refs-and-the-dom.html

Ответ 5

это работает для меня

  ref={element => {  
          //Clear text after Input
                this.attendee = element
              }}
              onSubmitEditing={this.handleAddPress}

and this.attendee.setNativeProps({ text: '' })//Очистить текст после ввода

Ответ 6

Следующий пример кода:

<TextInput 
    onChangeText={(text) => this.onChangeText(text)} 
    ref={component => this._textInput = component}
    onSubmitEditing={() => {
       this.clearText()
     }}
/>

clearText(){
  this._textInput.setNativeProps({ text: ' ' });

  setTimeout(() => {
    this._textInput.setNativeProps({ text: '' });
   },3);
}

Ответ 7

Я делаю этот код для очистки TextInput в React Native OnSubmitEditing вы можете проверить мою закуску: https://snack.expo.io/@andreh111/clear-textinput-onsubmitediting

Вот код:

state = {
    searchInput:'',
    clearInput:false
}
render(){
  return(



  <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
    <TextInput 
            style={{
              borderColor:'black',
              borderWidth:1,
              width:200,
              height:50
            }}
              onChangeText={(searchInput)=>this.setState({
                searchInput
              })}
              value={!this.state.clearInput ? this.state.searchInput : null}
              onSubmitEditing={()=>{
                this.setState({
                  clearInput:!this.state.clearInput,

                })

              }}
     />
</View>
)

}

Ответ 8

Это сработало для меня..

Инициируйте myTextInput в конструкторе:

this.myTextInput = React.createRef();

Добавьте ссылку в функцию рендеринга:

<Input ref={this.myTextInput} />

И тогда вы можете позвонить

this.myTextInput.current.value='';

Ответ 9

Одним из более простых подходов будет использование свойства value в TextInput и использование объекта значения состояния компонента для установки значения textInput.

state = {
   inputTextValue : '',
}

submitText = () => {
    //handle the click action

    //add this line at the end of the function after you are done handling with the input text value.
    this.state.inputTextValue = '';
}  

<TextInput 
       onChangeText={(text) => this.setState({ inputText: text })}
       placeholder="Monday breakfast"
       value={this.state.inputTextValue}
 />
 <TouchableOpacity 
       onPress={() => this.submitText()}>
       <Text>Submit</Text>
 </TouchableOpacity>

Ответ 10

 <TextInput
        ref={input => { this.name = input }}
   />

         this.name.clear();
         this.email.clear();
         this.password.clear();
         this.confirmPassword.clear();