首页 > 解决方案 > 如果未对表单进行任何更改,则禁用提交按钮

问题描述

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

在 angularjs 中,您可以使用等来执行此操作pristinedirty我如何在 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>

标签: javascripthtmlreactjsreact-bootstrapbootstrapvalidator

解决方案


由于您没有使用 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

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

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


推荐阅读