React - 如何将输入字段(受控)重置为默认值

Vid*_*dhi 1 javascript reactjs

我想在单击“恢复默认值”按钮时恢复所有输入字段和总计的默认值,但它不起作用。在我到目前为止的代码中,所有元素都包含在网格中。

我提到的SO问题是:

  1. 将所有元素包装在表单或 div 中并调用 reset()
  2. 在事件上使用 e.target.reset()。我用按钮的 onClick 事件尝试了这个,但说重置不是一个函数。

实现此功能的首选方式是什么?提前致谢!

class Test extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
    code1: this.props.defaults[0],
    code2: this.props.defaults[1],
    code3: this.props.defaults[2],
    total : 0
  };
  this.handleInput = this.handleInput.bind(this);
  this.restoreDefaults = this.restoreDefaults(this);
 }

handleInput() {
  //some logic
}

updateCode = (e, k) => {
    this.setState({
        [`code${k}`]: e.target.value
      },
      () => {
        this.updateTotal();
      });
  }

  updateTotal = () => {
    this.setState(prevState => ({
        total: (+prevState.code1 + +prevState.code2 + +prevState.code3),
      }),
      () => {
        if (this.state.total !== 100) {
          this.setState({
            isTotalInvalid: true
          });
        } else {
          this.setState({
            isTotalInvalid: false
          });
        }
      });
  }

  restoreDefaults() {
    this.setState({
      code1: this.props.defaults[0],
      code2: this.props.defaults[1],
      code3: this.props.defaults[2],
      total: 0,
    )};
  }

  render() {
    return (
    <Spacer>
     <Grid>
      <Grid.Row>
       <Grid.Column tiny={12} medium={10}>
          <input type="number" defaultValue={this.state.code1} min="0" max="100" onKeyPress={this.handleInput} onBlur={e => this.updateCode(e, 1)} />
       </Grid.Column>
       <Grid.Column tiny={12} medium={10}>
          <input type="number" defaultValue={this.state.code2} min="0" max="100" onKeyPress={this.handleInput} onBlur={e => this.updateCode(e, 2)} />
       </Grid.Column>
       <Grid.Column tiny={12} medium={10}>
          <input type="number" defaultValue={this.state.code3} min="0" max="100" onKeyPress={this.handleInput} onBlur={e => this.updateCode(e, 3)} />
          Total Field:

          <span fontSize={14} weight={700}>{this.state.total}</span>
         </Grid.Column>
        </Grid.Row>
        <Grid.Row>
          <Button text="Restore Default" type="button" onClick= 
            {this.restoreDefaults} />
        </Grid.Row>
       </Grid>
      </Spacer>
       );
    }
  }

export default Test;
Run Code Online (Sandbox Code Playgroud)

Bri*_*son 5

受控输入需要两个部分。

  • Avalue提供给输入
  • 变更处理程序

请记住:defaultValue仅设置输入值一次。之后就没有效果了。

这允许您以编程方式控制输入的值。

我在下面添加了一个非常简化的示例。

在此示例中,我们通过将值保持在状态来控制它们。但这可能在 props 或 redux 中或任何地方。

然后,当我们想要重置表单时,只需将状态更改回其初始值即可。由于input是通过valueprop(我们的状态)通知的,因此它会有效地重置。

class Example extends React.Component {
  state = {
    code1: '',
    code2: '',
    code3: '',
  }
  
  handleChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  }
  
  handleReset = () => {
    this.setState({
      code1: '',
      code2: '',
      code3: '',
    });
  }

  render() {
    return (
      <div>
        <div>
          <input 
            type="number" 
            name="code1"
            value={this.state.code1} 
            onChange={this.handleChange} 
            min="0" 
            max="100" 
          />
        </div>
        <div>
          <input 
            type="number" 
            name="code2"
            value={this.state.code2} 
            onChange={this.handleChange} 
            min="0" 
            max="100" 
          />
        </div>
        <div>
          <input 
            type="number" 
            name="code3"
            value={this.state.code3} 
            onChange={this.handleChange} 
            min="0" 
            max="100" 
          />
        </div>
        <button onClick={this.handleReset}>Reset</button>
      </div>
    )
  }
}

ReactDOM.render(<Example/>, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />
Run Code Online (Sandbox Code Playgroud)