javascript - 在发送表单之前调度 onBlur
问题描述
我有一个带有电子邮件的表单,它在后端创建一个帐户,用户可以在此步骤中更改电子邮件。这段代码通过将函数放在 onBlur 中来做到这一点,但是如果我更改输入中的电子邮件并且不离开该字段,则不会发生 onBlur。我可以直接点击提交,发送我的旧电子邮件以创建帐户。
这是代码:
const SendForm = ({ submit }) => {
const onLabelSubmit = () => async (event, newValue, name) => {
handleLabelSubmit(newValue, name);
};
const submitForm = () => {
// validations
submit();
};
const handleSubmitAccount = (e) => {
e.preventDefault();
dispatch(submitAccount(field.name, field.email))
.then(() => {
submitForm();
});
};
return (
<form onSubmit={handleSubmitAccount}>
<Field
id="email"
name="email"
label="label"
onBlur={onLabelSubmit(label.email)}
/>
<Button type="submit">
Submit Form
</Button>
</form>
);
};
有什么办法可以做 onBlur 所做的事情,但是当我点击提交按钮时?我需要改善体验并避免错误。
谢谢!
解决方案
使用 .向组件添加状态useState
。它不会在您的输入字段中onBlur
使用onChange
和添加value
属性,而是会在每个用户输入时触发,因此您将始终拥有最新的给定电子邮件和用户名。
const SendForm = ({ submit }) => {
const [fields, setFields] = useState({ name: '', email: '' })
const onFieldChange = () => async (newValue, name) => {
setFields({ ...fields, [name]: newValue });
};
const submitForm = () => {
// validations
submit();
};
const handleSubmitAccount = (e) => {
e.preventDefault();
dispatch(submitAccount(field.name, field.email))
.then(() => {
submitForm();
});
};
return (
<form onSubmit={handleSubmitAccount}>
<Field
id="email"
name="email"
label="label"
value={fields.email}
onChange={onFieldChange(label.email)}
/>
<Button type="submit">
Submit Form
</Button>
</form>
);
};
推荐阅读
- gis - 导入的 GIS 文件和网络之间未对齐(节点具有 X 和 Y 坐标) - NetLogo
- c# - 如何根据“sender”在“MouseDown”事件中设置WPF DataGrid(mvvm)的属性?
- javascript - 此过程是否用于读取和更新模块级数组变量“线程安全”?
- laravel - Laravel 组件的钩子?
- reactjs - 在 React Native 中使用动态名称的 Image Require 模块
- python-3.x - 稀疏一热编码特征的内存问题
- moodle - 如何为moodle服务器设置redis缓存?
- python - debug_toolbar 模块在 docker down / docker up 后没有持久化
- python - 如何在 python dm-script 中获取当前文件路径
- android - 如何从 Retrofit、RxJava、Android 中的所有请求中发出多个请求和响应