2 回答
TA贡献1851条经验 获得超5个赞
有多种方法可以做到这一点,但我建议在初始化为 true 的状态下跟踪按钮的禁用状态。
现在在每次更改电子邮件时运行的useEffect中更改禁用状态,并根据您的验证将其设置为 true 或 false。
import React from "react";
// Modify this function as per your needs
const validateEmail = email => typeof email === "string" && email.includes("@");
export default function App() {
const [email, setEmail] = React.useState("");
const [isDisabled, setIsDisabled] = React.useState(true);
const onEmailChange = event => {
setEmail(event.target.value);
};
React.useEffect(() => {
setIsDisabled(!validateEmail(email));
}, [email]);
return (
<>
<input
type="text"
value={email}
onChange={onEmailChange}
placeholder="Insert user email"
/>
<button disabled={isDisabled}>Add</button>
</>
);
}
TA贡献1775条经验 获得超11个赞
您可以使用regexorder 通过onChange()属性检查输入值是否为电子邮件。
import React from "react";
const regex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i;
export default function App() {
const [isDisabled, setDisibility] = React.useState(true);
const checkEmail = e => {
setDisibility(!regex.test(e.target.value));
}
return (
<div>
<input onChange={checkEmail} placeholder="email address" />
<button disabled={isDisabled}>add</button>
</div>
);
}
https://codesandbox.io/s/dry-sun-votmt?fontsize=14&hidenavigation=1&theme=dark
添加回答
举报