如何使用react和javascript修复在禁用和启用状态之间切换的按钮?
如果电子邮件有效,则启用“添加”按钮。如果电子邮件无效,则“添加”按钮被禁用 下面是我的代码如何使用react和javascript修复在禁用和启用状态之间切换的按钮?,javascript,reactjs,Javascript,Reactjs,如果电子邮件有效,则启用“添加”按钮。如果电子邮件无效,则“添加”按钮被禁用 下面是我的代码 function Parent() { const [email, setEmail] = useState(''); const [isDisabled, setIsDisabled] = React.useState(true); const regex = /^(?:"[ .a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$
function Parent() {
const [email, setEmail] = useState('');
const [isDisabled, setIsDisabled] = React.useState(true);
const regex = /^(?:"[ .a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*"|[.a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*)@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
const isValid = (value)=> {
return regex.test(String(value).toLowerCase());
}
const onEmailChange = (event: any) => {
setEmail(event.target.value);
};
useEffect(() => {
setIsDisabled(!isEmail(email));
}, [email]);
return (
<input
type="text"
onChange={onEmailChange}/>
<button disabled={isDisabled}>add</button>
);
}
函数父函数(){
const[email,setEmail]=useState(“”);
const[isDisabled,setIsDisabled]=React.useState(true);
(3)政府官员在现现阶段的regex=///^(((:::::::::::::::::::::::::::::::::::::(a-z0-10-9.5-9.5 5 5-5-5 5 5 5.5.5.5.5-10-0-10-10-10-10-10-10-10-9.5 5 5 5 5 5 5 5 5 5 5 5 5 5.5.5.5.5.5)及(((:::::::::::::::::::,,,,,,,,,,,,,,,,,,,,,,,,,//////////////////////=,,,,,,,,,,,,,[[[[[[[[[[[[[[[[[[[[[[[:[a-z0-9-]*[a-z0-9])?\)*[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
常量isValid=(值)=>{
返回regex.test(字符串(值).toLowerCase());
}
const onEmailChange=(事件:any)=>{
setEmail(event.target.value);
};
useffect(()=>{
setIsDisabled(!isEmail(email));
},[电邮];
返回(
添加
);
}
上面的正则表达式工作得非常完美。但问题是,当我键入电子邮件时,比如说“user@”,然后当用户键入下一个字符时,添加按钮被禁用,比如说现在电子邮件是“user@i“然后启用“添加”按钮。现在,当用户输入“user@i.“然后,当此操作发生时,“添加”按钮被禁用并启用”user@i.i“等等
我如何纠正这种行为???有人能帮我吗。谢谢。您的问题在于正则表达式,它不会检查电子邮件的结尾,您需要使用以下内容更新您的正则表达式
const regex_email = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const regex\u email=/^([^()[\]\\,;:\s@\“]+(\.[^()[\]\,;:\s@\“]+)*(\“+\”)((\[[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[1,3}.]0-9]{1,3}.[1,3}.];
演示:谢谢,它在这里给了我不必要的转义字符s@\”,(\“+”)。你能分享完整的电子邮件吗?我的意思是我在s@\”,(\“+”)处得到了错误不必要的转义字符