javascript - 如果未对表单进行任何更改,则禁用提交按钮
问题描述
我有一个使用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 形式,我将解释您需要如何实现它的逻辑
因此,您的状态将具有如下格式的键和值,这些是预先填充的值
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
由于状态已更新,您的按钮已启用
我希望这可以更好地理解这个问题
推荐阅读
- apache-kafka - 你能解释一下socket.timeout.ms吗?
- google-compute-engine - 是否可以为 Kubernetes GKE 节点池获取 GCP 的 ANY 发行版?
- c - 我们可以在 C 中的不同连续行中采用不同的数据类型输入吗
- javascript - 即使在 CSS 开发工具中可见,机车内容也不可见
- sql - 如何获取第一次记录后发生的任何更改值的emp id
- azure - 如何有条件地跳过使用 terraform 创建/实施的 terraform 资源的一部分
- javascript - 将数据存储到文件时发生错误 SyntaxError: JSON 输入意外结束
- python-asyncio - 如何从greenlet调用异步方法(剧作家)
- snowflake-cloud-data-platform - 雪花中的表关系
- java - 集成为统一本机插件的自定义 android 库导致重复类