清除和重置表单输入字段 [英] Clear and reset form input fields

查看:45
本文介绍了清除和重置表单输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含各种输入字段和两个按钮的表单;一份提交,一份取消.

I have a form containing various input fields and two buttons; one for submitting and one for cancelling.

<form id="create-course-form">
  <input type="text" name="course_Name" ref="fieldName">
  <input type="text" name="course_org" ref="fieldOrg">
  <input type="text" name="course_Number" ref="fieldNum">

  <input type="submit" name="saveCourse" value="Create">
  <input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse}>
</form>

我想要的是在单击取消按钮时清空所有输入.到目前为止,我已经通过使用每个输入的 ref 道具成功地做到了这一点.

What I want is to empty all inputs when the cancel button is clicked. So far I've managed to do this by using each input's ref prop.

cancelCourse(){
  this.refs.fieldName.value="";
  this.refs.fieldorg.value="";
  this.refs.fieldNum.value="";
}

但是,我想清空输入字段而不必单独清空每个字段.我想要类似的东西(jQuery):$('#create-course-form input[type=text]').val('');

However, I want to empty the input fields without having to empty each one seperately. I want something similar to this (jQuery): $('#create-course-form input[type=text]').val('');

推荐答案

这里的答案取决于您的输入是受控还是不受控制.如果您不确定或需要更多信息,请查看官方文档对 受控组件不受控制的组件.感谢 @Dan-Esparza 提供链接.

The answer here depends on whether or not your inputs are controlled or uncontrolled. If you are unsure or need more info on this, check out what the official docs say about controlled components and uncontrolled components. Thanks @Dan-Esparza for providing the links.

另外,请注意使用ref 中的字符串文字已弃用.改用标准回调方法.

Also, please note that using string literals in ref is deprecated. Use the standard callback method instead.

您可以清除整个表单,而不是单独清除每个表单域.

You can clear the entire form rather than each form field individually.

cancelCourse = () => { 
  document.getElementById("create-course-form").reset();
}

render() {
  return (
    <form id="create-course-form">
      <input />
      <input />
      ...
      <input />
    </form>
  );
}

如果您的表单没有 id 属性,您也可以使用 ref :

If your form didn't have an id attribute you could use a ref as well:

cancelCourse = () => { 
  this.myFormRef.reset();
}

render() {
  return (
    <form ref={(el) => this.myFormRef = el;}>
      <input />
      <input />
      ...
      <input />
    </form>
  );
}


清除带有受控字段的表单

如果您使用受控表单字段,您可能必须明确重置表单内的每个组件,具体取决于您的值在状态中的存储方式.


Clearing a form with controlled fields

If you are using controlled form fields, you may have to explicitly reset each component inside your form, depending on how your values are stored in the state.

如果它们是单独声明的,则需要明确地重置每一个:

If they are declared individually, you need to reset each one explicitly:

cancelCourse = () => { 
  this.setState({
    inputVal_1: "",
    inputVal_2: "",
    ...
    inputVal_n: "",
  });
}

render() {
  return (
    <input value={this.state.inputVal_1} onChange={this.handleInput1Change}>
    <input value={this.state.inputVal_2} onChange={this.handleInput2Change}>
    ...
    <input value={this.state.inputVal_n} onChange={this.handleInputnChange}>
  );
}

下面的演示:

class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      inputVal_1: "",
      inputVal_2: "",
      inputVal_3: "",
      inputVal_4: "",
      inputVal_5: "",
      inputVal_6: "",
      inputVal_7: "",
      inputVal_8: "",
      inputVal_9: "",
      inputVal_10: ""
    };
  }
  
  handleInput1Change = (e) => {
    this.setState({inputVal_1: e.target.value});
  }
  
  handleInput2Change = (e) => {
    this.setState({inputVal_2: e.target.value});
  }
  
  handleInput3Change = (e) => {
    this.setState({inputVal_3: e.target.value});
  }
  
  handleInput4Change = (e) => {
    this.setState({inputVal_4: e.target.value});
  }
  
  handleInput5Change = (e) => {
    this.setState({inputVal_5: e.target.value});
  }
  
  handleInput6Change = (e) => {
    this.setState({inputVal_6: e.target.value});
  }
  
  handleInput7Change = (e) => {
    this.setState({inputVal_7: e.target.value});
  }
  
  handleInput8Change = (e) => {
    this.setState({inputVal_8: e.target.value});
  }
  
  handleInput9Change = (e) => {
    this.setState({inputVal_9: e.target.value});
  }
  
  handleInput10Change = (e) => {
    this.setState({inputVal_10: e.target.value});
  }
  
  cancelCourse = () => { 
    this.setState({
      inputVal_1: "",
      inputVal_2: "",
      inputVal_3: "",
      inputVal_4: "",
      inputVal_5: "",
      inputVal_6: "",
      inputVal_7: "",
      inputVal_8: "",
      inputVal_9: "",
      inputVal_10: ""
    });
  }
  
  render() {
    return (
      <form>
        <input value={this.state.inputVal_1} onChange={this.handleInput1Change} />
        <input value={this.state.inputVal_2} onChange={this.handleInput2Change} />
        <input value={this.state.inputVal_3} onChange={this.handleInput3Change} />
        <input value={this.state.inputVal_4} onChange={this.handleInput4Change} />
        <input value={this.state.inputVal_5} onChange={this.handleInput5Change} />
        <input value={this.state.inputVal_6} onChange={this.handleInput6Change} />
        <input value={this.state.inputVal_7} onChange={this.handleInput7Change} />
        <input value={this.state.inputVal_8} onChange={this.handleInput8Change} />
        <input value={this.state.inputVal_9} onChange={this.handleInput9Change} />
        <input value={this.state.inputVal_10} onChange={this.handleInput10Change} />
        <input type="submit" name="saveCourse" value="Create" />
        <input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
      </form>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

不过,有一种更简洁的方法可以做到这一点.与其有 n 个状态属性和 n 个事件处理程序,每个输入一个,通过一些巧妙的编码,我们可以显着减少代码.

There is a cleaner way to do this though. Rather than having n state properties and n event handlers, one for each input, with some clever coding we can reduce the code dramatically.

在构造函数中,我们只声明了一个空对象,它将用于保存输入值.我们只使用一个输入处理程序并将我们要更改其值的输入元素的索引传递给它.这意味着单个输入的值在我们开始输入时生成.

In the constructor we just declare an empty object, which will be used to hold input values. We use only one input handler and pass it the index of the input element we want to change the value of. This means that the value of an individual input is generated the moment we start typing into it.

要重置表单,我们只需要再次将输入对象设置为空即可.

To reset the form, we only need to set our input object back to being empty again.

输入值为this.state.inputVal[i].如果 i 不存在(我们还没有在该输入中输入任何内容),我们希望该值是一个空字符串(而不是 null).

The input value is this.state.inputVal[i]. If i doesn't exist (we haven't typed anything yet into that input) we want the value to be an empty string (instead of null).

cancelCourse = () => { 
  this.setState({inputVal: {}});
}

render() {
  return (
    <form>
      {[...Array(n)].map(
        (item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} />
      )}
    </form>
  );
}

下面的演示:

class MyApp extends React.Component {
  constructor() {
    super();
    this.state = {
      inputVal: {}
    };
  }
  
  handleInputChange = (idx, {target}) => {
    this.setState(({inputVal}) => {
      inputVal[idx] = target.value;
      return inputVal;
    });
  }
  
  cancelCourse = () => { 
    this.setState({inputVal: {}});
  }
  
  render() {
    return(
      <form>
        {[...Array(10)].map(  //create an array with a length of 10
          (item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} />  //bind the index to the input handler
        )}
        <input type="submit" name="saveCourse" value="Create" />
        <input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
      </form>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("app"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

这篇关于清除和重置表单输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆