【问题标题】:Disable submit button if no change is done to the form如果未对表单进行任何更改,则禁用提交按钮
【发布时间】:2020-04-23 17:18:46
【问题描述】:

我有一个使用react-bootstrap 组件的表单,当表单加载时,字段将填充默认值,并且可以编辑这些字段。如果没有对表单进行任何更改,我想禁用我的提交按钮。如果对表单进行了任何更改,我希望提交按钮能够提交。

在 angularjs 中,您可以使用 pristine 、 dirty 等来执行此操作。我如何在 reactjs 中执行此操作并响应引导程序?

我的表单

<Form noValidate validated={validated} onSubmit={this.handleSubmit}>
   <div id="" className="pb-3 pr-lg-5 pr-xs-0">
      <div id="form_data" className="pb-3 pr-0">

         <Form.Group as={Row} controlId="formAddress">
            <Form.Label column sm="2" lg="4">
               <label className="label_type2">Address</label>
            </Form.Label>
            <Col sm="10" lg="8">
            <Form.Control type="text" defaultValue={login.userInfoLoading === true ? 'Loading...' : userInfoAddress.address} className="input_text" required />
            </Col>
         </Form.Group>

         <Form.Group as={Row} controlId="formPostalCode">
            <Form.Label column sm="2" lg="4">
               <label className="label_type2">Postal code</label>
            </Form.Label>
            <Col sm="10" lg="4">
            <Form.Control type="text" defaultValue={login.userInfoLoading === true ? 'Loading...' : userInfoAddress.cep} className="input_text" required />
            </Col>
         </Form.Group>
      </div>

      <Button type="submit" size="lg" variant="light" className="mt-5 mb-3 btn_type1" id="button_primary_clr">Update information</Button>
   </div>
</Form>

【问题讨论】:

  • 由于你没有使用 redux 表单,你需要通过编写自定义函数来处理它,因为 redux 表单有一个名为 isDirty 的属性!
  • @DILEEPTHOMAS 不,我正在为我的输入组件使用 react-bootstrap
  • 我已经添加了如何实现这一点的逻辑,请检查并告诉我!!

标签: javascript html reactjs react-bootstrap bootstrapvalidator


【解决方案1】:

由于你没有使用redux形式,我将解释你需要如何实现它的逻辑

因此您的状态将具有如下格式的键和值,这些是预先填充的值

state = {formValues:{firstName: 'John', secondName: 'Doe', Address: ''}, isFormDirty: false}

所以基于 isFormDirty 的初始状态,您可以禁用按钮,因为没有任何变化

现在您需要在顶层附加一个方法到 Form,因为发生了事件委托,您将从子输入中获取事件,因此假设 firstName 字段用户有现在更改了,您可以在组件加载时将对象作为内部状态

changedValues: {firstName: false, secondName: false, Address: false}

现在你有两个对象 changedValues 和 formValues

onFormHandleChange = (e) => {
 // compare the current value and pre populated value
  e.target.value === formValues[e.target.name]
// if its true
 changedValues[e.target.name] = true
 else false
}

所以基于这个 changedValues 对象,比如 Object.values(this.state.changedValues) 数组包含 true 你可以使 isFormDirty 为 true

由于状态更新,您的按钮已启用

我希望这可以更好地理解问题

【讨论】:

    猜你喜欢
    • 2019-07-19
    • 2023-04-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多