React中如何在密码输入框的onChange属性同时传入事件和confirm函数
解决方案
直接在id为password的输入框的onChange匿名回调内按顺序执行两个逻辑即可,event对象可以正常在回调内使用、传递给需要的方法:
// 修改原password输入框的onChange属性即可 <input type="password" required id="password" value={password} onChange={(e) => { // 执行原有赋值逻辑,保留event传递 setPassword(e.target.value) // 调用自定义confirm校验函数,此处传密码值即可,需要event的话直接传e参数就行 confirm(e.target.value) }} />
额外优化提示
- 你当前的
confirm函数只做了校验判断,没有存储校验结果,建议新增状态const [isPwdStrong, setIsPwdStrong] = useState(false),在校验通过时更新状态,后续可以结合该状态做密码强度提示、提交限制等逻辑。 - 现有的确认密码输入框
onChange仅调用了confirm函数,没有更新confirmPassword状态,会导致后续两次密码一致性判断失效,建议修改为:
<input type="password" required id="confirmPassword" value={confirmPassword} onChange={(e) => { setConfirmPassword(e.target.value) confirm(e.target.value) }} />
内容的提问来源于stack exchange,提问作者Navya Malhotra
相关产品推荐
相关产品推荐

