如何阻止Modal点击外部关闭?仅允许满足条件时点击Submit按钮关闭
解决方案
当然可以实现这个需求!要让你的密码修改Modal仅在点击满足条件的Submit按钮时才关闭,同时阻止点击Modal外部或按下Escape键触发关闭,只需要给Modal组件添加两个关键属性:
- 添加
backdrop={'static'}:这个属性会将Modal的背景层设置为“静态”,点击背景区域不会触发Modal关闭 - 添加
keyboard={false}:这个属性会禁用按下Escape键关闭Modal的默认行为
修改后的代码示例
<div> <Modal show={this.state.show} onHide={this.handleClose} backdrop={'static'} {/* 阻止点击外部关闭Modal */} keyboard={false} {/* 阻止按下Escape键关闭Modal */} > <Modal.Header> <Modal.Title>Change Password</Modal.Title> </Modal.Header> <Modal.Body> <form className="form-horizontal" style={{margin:0}}> <div className='password-heading'>This is the first time you have logged in.</div> <div className='password-heading'>Please set a new password for your account.</div> <br/> <label className="password">Password <input type={this.state.type} className="password__input" onChange={this.passwordStrength}/> <span className="password__show" onClick={this.showHide}>{this.state.type === 'input' ? 'Hide' : 'Show'}</span> <span className="password__strength" data-score={this.state.score} ><div className="strength_string">{this.state.strength}</div></span> </label> <br/> <label className="password">Confirm Password <input type={this.state.type} className="password__input" onChange={this.passwordStrength}/> </label> </form> <br/> </Modal.Body> <Modal.Footer> <Button onClick={this.submitPassword} disabled={this.state.isDisabled}>Submit</Button> </Modal.Footer> </Modal> </div>
补充说明
单独添加backdrop={'static'}只能阻止点击外部关闭Modal,但用户仍然可以通过按下Escape键关闭它。所以必须同时配置keyboard={false},才能完全确保Modal只有在你手动调用handleClose(也就是点击满足条件的Submit按钮时)才会关闭。
内容的提问来源于stack exchange,提问作者morne
相关产品推荐
相关产品推荐

