我有一个使用 React 钩子(Hook)创建的组件,该组件具有输入和复选框。我已将一个函数附加到输入以验证电子邮件地址。我在清除输入并禁用它的复选框上有一个功能。我正在尝试重写我的验证函数以在输入字段处于事件状态时运行,这样即使用户单击复选框以清除和禁用该字段然后再次单击它以重新启用它,验证也会再次运行并提示带有错误消息的用户输入电子邮件地址。到目前为止,我的输入设置了一个 onBlur 函数,该函数在用户输入和退出输入时立即运行验证。我需要维护此功能,但增加它以在启用输入时也运行。我有一个代码沙箱 here有关更多上下文和我的以下简短格式的组件:
import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import { Col, Row, Input, Checkbox } from "antd";
function validateEmail(value) {
const errors = {};
if (value === "") {
errors.email = "Email address is required";
} else if (!/\S+@\S+\.\S+/.test(value)) {
errors.email = "Email address is invalid";
}
return errors;
}
const CustomerDetails = ({ customer }) => {
const { contact = {} } = customer || {};
const [disableInput, setDisableInput] = React.useState(false);
const [errors, setErrors] = React.useState({});
const [inputValue, setInputValue] = React.useState(contact.email);
function onBlur(e) {
setErrors(validateEmail(e.target.value));
}
function clearInput() {
setInputValue(" ");
}
function handleInputChange(event) {
setInputValue(event.target.value);
}
function CheckboxClick(e) {
if (!disableInput) {
clearInput();
}
setDisableInput(prevValue => !prevValue);
setErrors({});
}
return (
<Container>
<Row>
<Col span={8}>
<StyledInput
value={inputValue}
onChange={handleInputChange}
disabled={disableInput}
onBlur={onBlur}
isError={!!errors.email}
/>
{errors.email && <ErrorDiv>{errors.email}</ErrorDiv>}
</Col>
<Col span={8}>
<Checkbox value={disableInput} onChange={CheckboxClick} /> EMAIL OPT
OUT
</Col>
</Row>
</Container>
);
};
const Container = styled.div`
text-align: left;
`;
const ErrorInput = ({ isError, ...remainingProps }) => (
<Input {...remainingProps} />
);
ErrorInput.propTypes = {
isError: PropTypes.bool
};
const StyledInput = styled(ErrorInput)`
max-width: 100%;
background: white;
&&& {
border: 2px solid ${props => (props.isError ? "#d11314" : "black")};
border-radius: 0px;
height: 35px;
}
`;
const ErrorDiv = styled.div`
color: #d11314;
`;
export default CustomerDetails;
最佳答案
你可以做类似的事情
function CheckboxClick(e) {
const isDisabled = !disableInput;
setDisableInput(isDisabled);
if (isDisabled) {
clearInput();
setErrors({});
} else {
setErrors(validateEmail(inputValue));
}
}
因此,首先更新 disabled
状态,然后根据它执行操作。
关于javascript - react / react Hook : I need to run a validation on an input field depending on active/inactive state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56548944/