【问题标题】:Clear an input field with Reactjs?使用 Reactjs 清除输入字段?
【发布时间】:2016-08-02 22:09:24
【问题描述】:

我在下面使用一个变量。

var newInput = {
   title: this.inputTitle.value,
   entry: this.inputEntry.value    
};

这是由我的输入字段使用的。

<input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />   
<textarea id="inputage" ref={el => this.inputEntry = el} className="form-control" />
<button className="btn btn-info" onClick={this.sendthru}>Add</button>

激活{this.sendthru} 后,我想清除输入字段。但是,我不确定如何做到这一点。

另外,如本例所示,有人指出我应该使用ref 属性作为输入值。我不清楚的是拥有{el =&gt; this.inputEntry = el} 到底意味着什么。在这种情况下el有什么意义?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    假设你已经完成了 'sendThru' 函数的 'this' 绑定。

    以下函数在触发方法时清除输入字段。

    sendThru() {
        this.inputTitle.value = "";
        this.inputEntry.value = "";
    }
    

    Refs可以写成内联函数表达式:

    ref={el => this.inputTitle = el}
    

    其中el 指的是组件。

    当 refs 像上面那样编写时,React 每次都会看到一个不同的函数对象,因此每次更新时,在使用组件实例调用 ref 之前,都会立即使用 null 调用 ref。

    阅读更多相关信息here

    【讨论】:

    • 你能稍微扩展一下 sendthru 函数的“this”绑定是什么意思吗?照原样,当我单击时,我收到 cannot read property value of undefined 的错误
    • 知道了。我没有使用this.refs.inputTitle.value="",而是使用了this.inputTitle="",它成功了。
    • 'sendThru' 是 onClick 函数的事件处理程序,React 建议在构造方法中绑定 'this' 引用。例如constructor() { this.sendThru = this.sendThru.bind(this)}' or if you are not using ES6 classes for react component you could bind the this key word in your render method as onClick={this.sendThru.bind(this)}`
    • 应该只是this.inputTitle.value = "";。 React 已弃用 this.refs: facebook.github.io/react/docs/…
    【解决方案2】:

    声明输入标签的值属性(即value= {this.state.name}),如果你想清除这个输入值你必须使用this.setState({name : ''})

    PFB工作代码供大家参考:

    <script type="text/babel">
        var StateComponent = React.createClass({
            resetName : function(event){
                this.setState({
                    name : ''
                });
            },
            render : function(){
                return (
                    <div>
                        <input type="text" value= {this.state.name}/>
                        <button onClick={this.resetName}>Reset</button>
                    </div>
                )
            }
        });
        ReactDOM.render(<StateComponent/>, document.getElementById('app'));
    </script>
    

    【讨论】:

    • 来自 Angular:这似乎是一种双向绑定方法,我喜欢。
    • 这仅在您还添加逻辑以更新 this.state.name 时才有效,只要输入中有按键。否则冻结为'',初始值为'this.state.name
    • Jhee whizz,唯一对我有用的解决方案。谢谢。
    • 你并不总是想要这个,每次状态变化都会导致重新渲染,有时这正是你想要的,但有时你想要更具体
    【解决方案3】:

    我不太确定语法 {el => this.inputEntry = el},但是在清除输入字段时,您会像您提到的那样分配一个 ref。

    <input type="text" ref="someName" />
    

    然后在你使用完输入值后的onClick函数中,使用...

    this.refs.someName.value = '';
    

    编辑

    实际上 {el => this.inputEntry = el} 与我认为的 this 相同。也许有人可以纠正我。 el 的值必须从某个地方传入,以充当参考。

    function (el) {
        this.inputEntry = el;
    }
    

    【讨论】:

      【解决方案4】:

      我有一个使用 React 钩子的 @Satheesh 类似的解决方案:

      状态初始化:

      const [enteredText, setEnteredText] = useState(''); 
      

      输入标签:

      <input type="text" value={enteredText}  (event handler, classNames, etc.) />
      

      在事件处理函数内部,用输入表单中的数据更新对象后,调用:

      setEnteredText('');
      

      注意:这被描述为“双向绑定”

      【讨论】:

        【解决方案5】:

        你可以使用 input type="reset"

        <form action="/action_page.php">
          text: <input type="text" name="email" /><br />  
          <input type="reset" defaultValue="Reset" />  
        </form>
        

        【讨论】:

          【解决方案6】:

          在 React v 16.8+ 之后,您可以使用钩子

          import React, {useState} from 'react';
          
          const ControlledInputs = () => {
            const [firstName, setFirstName] = useState(false);
          
            const handleSubmit = (e) => {
              e.preventDefault();
              if (firstName) {
                console.log('firstName :>> ', firstName);
              }
            };
          
            return (
              <>
                <form onSubmit={handleSubmit}>
                    <label htmlFor="firstName">Name: </label>
                    <input
                      type="text"
                      id="firstName"
                      name="firstName"
                      value={firstName}
                      onChange={(e) => setFirstName(e.target.value)}
                    />
                  <button type="submit">add person</button>
                </form>
              </>
            );
          };
          

          【讨论】:

          • 更好地展示我的答案。非常完整。
          • 如果 onChange 在
            标签上怎么办?我不想在每个输入上添加 onChange。您如何处理这个问题?
          【解决方案7】:

          onClick 事件时

          this.state={
            title:''
          }
          
          sendthru=()=>{
            document.getElementByid('inputname').value = '';
            this.setState({
               title:''
          })
          }
          
          <input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />   
          <button className="btn btn-info" onClick={this.sendthru}>Add</button>
          

          【讨论】:

            【解决方案8】:

            你可以使用useState:

            import React, { useState } from 'react';
            const [inputTitle, setInputTitle] = useState('');
            

            然后为您的输入组件添加价值:

            render() {
            <input type="text" onChange={(e) => setInputTitle(e.target.value)} 
            value={inputTitle} />
            <button onClick={handleSubmit} type="submit">Submit</button>
            }
            

            在您的提交处理函数上:

            setInputTitle('');
             document.querySelector('input').defaultValue = '';
            
             
            

            【讨论】:

              【解决方案9】:

              如果您不想使用 useState 钩子,现在可以使用 useRef 钩子获得一些魔力:

              function MyComponent() {
                const inputEl = useRef(null);
                const onButtonClick = () => {
                  // @ts-ignore (us this comment if typescript raises an error)
                  inputEl.current.value = "";
                };
                return (
                  <>
                    <input ref={inputEl} type="text" />
                    <button onClick={onButtonClick}>Clear input</button>
                  </>
                );
              }
              

              正如我所提到的,如果您使用的是useState,那是最好的方法。我还想向您展示这种特殊的方法。

              【讨论】:

                【解决方案10】:

                我清除表单输入值的方法是在表单标签中添加一个 id。 然后当我处理提交时,我调用 this.clearForm()

                然后在 clearForm 函数中使用 document.getElementById("myForm").reset();

                import React, {Component } from 'react';
                import './App.css';
                import Button from './components/Button';
                import Input from './components/Input';
                
                class App extends Component {  
                  state = {
                    item: "", 
                    list: []
                }
                
                componentDidMount() {
                    this.clearForm();
                  }
                
                handleFormSubmit = event => {
                   this.clearForm()
                   event.preventDefault()
                   const item = this.state.item
                
                    this.setState ({
                        list: [...this.state.list, item],
                            })
                
                }
                
                handleInputChange = event => {
                  this.setState ({
                    item: event.target.value 
                  })
                }
                
                clearForm = () => {
                  document.getElementById("myForm").reset(); 
                  this.setState({
                    item: ""
                  })
                }
                
                
                
                  render() {
                    return (
                      <form id="myForm">
                      <Input
                
                           name="textinfo"
                           onChange={this.handleInputChange}
                           value={this.state.item}
                      />
                      <Button
                        onClick={this.handleFormSubmit}
                      >  </Button>
                      </form>
                    );
                  }
                }
                
                export default App;
                

                【讨论】:

                • 你为什么不直接使用 ref 而不是 id + document.getElementById ?我不认为这是对已接受答案的改进
                • 扮演魔鬼的拥护者,裁判系统是在这个答案三周后引入的,16.3,所以也许他不知道更好的方法。但我同意需要更新。
                猜你喜欢
                • 2016-07-11
                • 1970-01-01
                • 2014-06-12
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2019-11-22
                • 2020-12-27
                • 2020-12-12
                相关资源
                最近更新 更多