【问题标题】:Clear React Native TextInput清除 React Native TextInput
【发布时间】:2017-12-28 05:20:24
【问题描述】:

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

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

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    您也可以将&lt;TextInput/&gt;的值设置为与状态相同,并在使用数据后将状态设置回空字符串:

    //state
    const [state, setState] = useState({
      name: '',
      lastname: ''
    })
    
    //functions
    const newUser = () => {
    // Do your magic and after
      setState({
        name: '',
        lastname: ''
      })
    }
    
    const handleOnChange = () => {
      setState({
        // change your state
      })
    }
    
    //render
    <TextInput
      value={state.name}
      placeholder='Name'
      onChangeText={/* execute your handleOnChange() */}
    />
    
    <TextInput
      value={state.lastname}
      placeholder='Lastname'
      onChangeText={/* execute your handleOnChange() */}
    />
    
    <Button title='Saved' onPress={() => newUser()} />
    

    希望有用!

    【讨论】:

      【解决方案2】:

      对于 RN > 0.6

      const [msg, setMsg] = useState()
      

      在 TextInput 中使用值

      <TextInput 
          onChangeText={(txt) => setMsg(txt)}}
          value={msg}
      />
      

      然后像这样在按钮按下功能中设置状态

      const pressButton = () => {
          setMsg('')
      }
      

      【讨论】:

        【解决方案3】:

        为我工作...

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

        调用后函数

        clearMsg(){
        
            this.textInput.state.value = ''
        }
        

        【讨论】:

        • 您不应该像这样直接分配给状态。 this.textInput.state.value = '' 使用 setState 代替 this.textInput.setState({value: ''})
        【解决方案4】:

        对于 iOS,它会给出默认的明文按钮。

        <TextInput clearButtonMode="always" />
        

        the doc

        【讨论】:

        • 对于android,你需要维护状态并相应地改变。
        • 如何维护android的状态?因为我在 android 中看不到清除按钮
        【解决方案5】:

        因为您使用的是函数式组件,所以您可以按如下方式使用 Hooks。如果你有条件渲染你的代码检查 todoInput 是否在传递给 useEffect 的函数中定义。我假设你的状态变量在依赖列表中被称为 todoText。

        import {useRef, useEffect} from 'react';
        
        
        let AddTodo = ({ dispatch }) => {
            const todoInput = useRef();
            useEffect(()=>todoInput.current.clear(),[todoText]);
        
              return (
                  <TextInput 
                      ref={todoInput}
                      onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } } 
                  />
              )
            }
        

        【讨论】:

          【解决方案6】:

          React-Native 使用来自 native-base 的 Input 组件。 这对我有用:

          <Input ref={input => {this.textInput = input;}}
          

          然后:

          this.textInput._root.clear();
          

          注意:不必使用 React.createRef() 来初始化。

          【讨论】:

            【解决方案7】:

            一种更简单的方法是使用TextInputvalue 属性并使用组件的状态值对象来设置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>
            

            【讨论】:

            • 应该是 this.setState({ inputTextValue: '' }) 而不是 this.state.inputTextValue = '' & 这可能是最好的方法
            • setState({inputTextValue : ''}) submitText() 之前缺少this
            【解决方案8】:

            在我的功能组件上,我与 submitHandler 一起调用另一个函数,该函数将负责清除文本

            const [text, setText] = useState('');
             const anotherFunc = (val) =>{
                    setText('');
                }
            
            
                return (
                    <View>
                        <TextInput 
                        value ={text}
                        onChangeText ={changeHander}
                        placeholder = 'Add '
                       />
                        <Button 
                        title = "Add Something "
                        onPress = {()=>  {submitHandler(text) , anotherFunc(text)}}
                        />
            
                    </View>
                )
            

            【讨论】:

              【解决方案9】:
                    this.state = {
                         commentMsg: '',
                    }
              
              after submittion 
                   if (response.success)
                   {
                          this.commentMsg.clear();        //TODO me
                   }
              
              
                <TextInput
                   style={styles.textInput}
                   multiline={true}
                   ref={input => {
                   this.commentMsg = input
                     }}
                   onChangeText={(text) => this.setState({commentMsg: text})}
                   placeholder ='Comment'/>
              

              【讨论】:

                【解决方案10】:

                感谢@André Abboud 在您的帮助下,我能够清除我的 TextInput 字段,但根据我的自定义 TextInput,我在实现上做了一些细微的改变。

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

                我所做的是:

                在 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>
                  ...
                

                在 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>
                
                  ...
                

                【讨论】:

                • 欢迎来到 SO!请检查您的答案,因为它已作为代码发布。
                【解决方案11】:
                 <TextInput
                        ref={input => { this.name = input }}
                   />
                
                         this.name.clear();
                         this.email.clear();
                         this.password.clear();
                         this.confirmPassword.clear();
                

                【讨论】:

                  【解决方案12】:

                  这对我有用..

                  在构造函数中初始化 myTextInput:

                  this.myTextInput = React.createRef();
                  

                  在渲染函数处添加引用:

                  <Input ref={this.myTextInput} />
                  

                  然后你就可以打电话了

                  this.myTextInput.current.value='';
                  

                  【讨论】:

                    【解决方案13】:

                    我正在使用原生基地 这就是我的工作方式

                    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

                    【讨论】:

                    • 发现这个错误:TypeError: _react3.default.createRef is not a function。 (在 '_react3.default.createRef()' 中,'_react3.default.createRef' 是未定义的)
                    • in react 16 > 构造函数中不需要添加createRef
                    【解决方案14】:

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

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

                    在渲染函数处:

                    &lt;TextInput ref={this.myTextInput} /&gt;

                    然后你就可以打电话了

                    this.myTextInput.current.clear();

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

                    【讨论】:

                    • 这个问题是关于 react-native 的,你的回答是针对 react 的。
                    • 这对我有用,而不是 clear.. this.myTextInput.current.value = '';
                    • 我浪费了 15 分钟才发现它不适用于 react-native。请坚持提问的内容。
                    • 这在 react-native 中对我有用。 just clear 没有,但 current.clear 正是我所需要的
                    • myTextInput.current.clear();工作正常。谢谢
                    【解决方案15】:

                    以下代码示例:

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

                    【讨论】:

                    • 我最终也想出了这个。这是唯一对我有用的。不知道为什么。
                    【解决方案16】:

                    我编写此代码用于清除 React Native OnSubmitEditing 中的 TextInput 你可以查看我的零食: 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>
                    )
                    
                    }
                    

                    【讨论】:

                      【解决方案17】:

                      这对我有用

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

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

                      【讨论】:

                        【解决方案18】:

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

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

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

                        【讨论】:

                        • 不错。谢谢你。
                        • 我在 iOS 上试过,但它不起作用。 TextInput 仍然保留旧值
                        • @NguyễnAnhTuấn 我已经尝试了最新版本的 RN (0.55.4),它仍然可以在 IOS 上运行。
                        • @NguyễnAnhTuấn @Kawatare267 @simonthumper 刚刚确认。 .clear() 不适用于新的 RN (0.55)。你们找到工作了吗?
                        • 我确认.clear() 只能在 Android 上运行,而在 iOS 上不起作用。问题链接:github.com/facebook/react-native/pull/18278,我们可以使用此模块解决问题:github.com/agiletechvn/react-native-text-input-enhance
                        猜你喜欢
                        • 2021-03-29
                        • 1970-01-01
                        • 2022-12-17
                        • 1970-01-01
                        • 1970-01-01
                        • 2019-01-10
                        • 1970-01-01
                        • 2018-11-08
                        • 2016-04-11
                        相关资源
                        最近更新 更多