简体   繁体   English

如何使用按钮重置反应表单输入值(与状态相关)?

[英]How to reset the react form input value (which is tied to a state) with a button?

How to reset the react form input value (which is tied to a state) with a button?如何使用按钮重置反应表单输入值(与状态相关)?

<Form.Group controlId="availabilityOborotDoc">
  <Form.Label>Documents</Form.Label>
  <Form.Control
    type="number"
    name="availabilityOborotDoc"
    required
    readOnly
    value={this.state.settings.availabilityOborotDoc}
  />
  <Link
    to={{
      pathname: `/ost-docs`,
      state: {
        settings: this.state.settings,
        isSelectDoc: true,
        isEdit: isEdit,
        isCreate: isCreate
      }
    }}
  >
    <Button variant="primary" disabled={isView}>
      Choose document
    </Button>
  </Link>
  <Button
    variant="warning"
    disabled={isView}
    onClick={() => {
      this.setState(prevState => ({
        settings: {
          ...prevState.settings,
          availabilityOborotDoc: null
        }
      }));
      this.forceUpdate();
    }}
  >
    Reset
  </Button>
</Form.Group>;

The Reset button I implemented clears the state field allright but doesn't set the value in input... (apparently it remembers the previous one)我实现的重置按钮清除了状态字段,但没有在输入中设置值......(显然它记得上一个)

Update the state to an empty string instead of null and it will work.将状态更新为空字符串而不是null它将起作用。

Check out this link for a little more explanation (at least it seems relevant?).查看此链接以获得更多解释(至少它看起来相关?)。 My assumption is that because react treats an input with null value as uncontrolled, it will leave the current value.我的假设是,因为 react 将具有null值的输入视为不受控制,所以它会保留当前值。

Here is a simplified example:这是一个简化的示例:

 class Example extends React.Component { constructor(props) { super(props); this.state = { settings: { availabilityOborotDoc: '12345' } } } render() { console.log(this.state.settings) return ( <div> <input readOnly value={this.state.settings.availabilityOborotDoc} /> <button onClick={() => { this.setState(prevState => ({ settings: { ...prevState.settings, availabilityOborotDoc: '' } })); }} > Reset </button> </div> ) } } ReactDOM.render(<Example />, document.getElementById('root'));
 <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"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM