Javascript 清除 React Native TextInput

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45249807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:58:37  来源:igfitidea点击:

Clear React Native TextInput

javascriptreact-native

提问by Dave Pile

Working through the Redux AddTodo example in React Native. The first AddTodo example below uses state to store the TextInput value and works fine.

在 React Native 中完成 Redux AddTodo 示例。下面的第一个 AddTodo 示例使用 state 来存储 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}) } } />
        );
    }
}

However following a few of the Redux examples, the following code is much shorter and also works except that the TextInputvalueis not cleared after submitting

但是,在一些 Redux 示例之后,以下代码要短得多并且也有效,只是TextInputvalue提交后未清除

let AddTodo = ({ dispatch }) => {

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

Is there any way I can clear the InputText value from onSubmitEditing?

有什么方法可以清除 onSubmitEditing 中的 InputText 值?

回答by Kawatare267

Add ref to your TextInput, for example:

将 ref 添加到您的 TextInput,例如:

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

then call this.textInput.clear()to clear your input value

然后调用this.textInput.clear()以清除您的输入值

回答by Aseem

For iOS, it will give the default clear text button.

对于 iOS,它将提供默认的明文按钮。

<TextInput clearButtonMode="always" />

See the doc

查看文档

回答by Marcio S Galli

According to changes and recommendations after React 16.3, you will need to retrieve the ref at your constructor using React.createRef:

根据React 16.3之后的更改和建议,您需要使用 React.createRef 在构造函数中检索 ref:

At constructor function: this.myTextInput = React.createRef();

在构造函数中: this.myTextInput = React.createRef();

At render function:

在渲染功能:

<TextInput ref={this.myTextInput} />

<TextInput ref={this.myTextInput} />

And then you can call

然后你可以打电话

this.myTextInput.current.clear();

this.myTextInput.current.clear();

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

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

回答by Fadi Abo Msalam

I am using Native baseand here is how i have made it work

我正在使用Native 基础,这是我如何使它工作

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

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

then whenever i want to clear i use

然后每当我想清除我使用

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

reference https://github.com/facebook/react-native/issues/18843

参考https://github.com/facebook/react-native/issues/18843

回答by Hansa Tharuka

this works for me

这对我有用

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

andthis.attendee.setNativeProps({ text: '' })//Clear text after Input

this.attendee.setNativeProps({ text: '' })// 输入后清除文本

回答by Gurbela

Following code sample:

以下代码示例:

<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);
}

回答by Raeygzz

Thanks @André Abboud by your help i was able to clear my TextInput field but according to my custom TextInput, i made a slight change in implementantion.

感谢@André Abboud 在您的帮助下,我能够清除我的 TextInput 字段,但根据我的自定义 TextInput,我对实现进行了轻微更改。

Please review the code and approach used for implementation. As far as i know now my requirement of clearing the TextInput as i needed is fullfilled and if required for any changes please notify in comment.

请查看用于实现的代码和方法。据我所知,我现在根据需要清除 TextInput 的要求已满,如果需要进行任何更改,请在评论中通知。

And what i did to make it work is:

我为使其工作所做的是:

In setupSender.js

在 setupSender.js 中

  ...
  this.state = {
    clearInput: false,
    ...
  }

  ...           
  setupSenderSubmit = () => {
      ...
      this.setState({                             
        clearInput: !this.state.clearInput,
      })
      ...
  }
  ...
      <CustomTextInput
        labelText="First Name" 
        onChangeText={(firstName) => this.setState({ firstName })}
        clearInput={this.state.clearInput}
        value={this.state.firstName}
        returnKeyType={ 'next' }
        autoFocus={true}
        onSubmitEditing={() =>  this.input2.current.focus()}
      ></CustomTextInput>
  ...

And in CustomTextInput.js

在 CustomTextInput.js 中

  this.state={
    clearInput: this.props.clearInput, 
  }

  ...

  static getDerivedStateFromProps = (props, state) => { 
    if (props.clearInput !== '' || props.clearInput !== undefined) {
      return {
        clearInput: props.clearInput
      }
    }
    return null;
  }

  ...

    <TextInput 
      label={this.props.label} 
      value={!this.state.clearInput ? this.state.text : null}
      onChangeText={(text) => {
          this.setState({text});
          this.props.onChangeText(text)
        }
      }
    </TextInput>

  ...

回答by mharindu

This worked for me..

这对我有用..

Init myTextInput at the constructor:

在构造函数中初始化 myTextInput:

this.myTextInput = React.createRef();

Add the reference at render function:

在渲染函数中添加引用:

<Input ref={this.myTextInput} />

And then you can call

然后你可以打电话

this.myTextInput.current.value='';

回答by Ezio

One simpler approach will be to use the valueproperty of TextInputand use the component's state value object to set the value of textInput.

一个简单的方法将使用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.
     setState({inputTextValue : ''})
}  

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

回答by Keshav Gera

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

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