我使用带有输入字段的React钩子创建了一个组件,每当用户将该字段留空或输入错误格式时,该字段都会运行电子邮件的验证功能。我在输入旁边还有一个复选框,其中有一个功能,该功能可以在用户单击输入字段时将其禁用。我现在遇到的问题是,即使该复选框禁用了该字段,与格式相关的错误消息仍会显示在下方。每当用户单击复选框时,我都试图清除错误消息并使输入字段显示为灰色。我有一个在此处运行的codeandbox:https://codesandbox.io/s/friendly-breeze-2ly5h,下面是我的完整组件
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import {
Col, Row, Icon, Input, Tooltip
} from 'antd'
import Checkbox from '../elements/Checkbox'
import Markup from '../core/Markup'
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 = {}, account = {}, site = {} } = 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() {
if (!disableInput) {
clearInput()
}
setDisableInput(prevValue => !prevValue)
}
return (
<Container>
<Row>
<Col span={10}>
<h4>
PRIMARY CONTACT EMAIL
</h4>
</Col>
</Row>
<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={2} />
<Col span={8}>
<StyledCheckbox
value={disableInput}
onChange={CheckboxClick}
/> EMAIL
OPT OUT{' '}
</Col>
</Row>
</Container>
)
}
const Container = styled.div`
text-align: left;
`
const StyledCheckbox = styled(Checkbox)`
&&& {
background: white;
input + span {
width: 35px;
height: 35px;
border: 2px solid ${({ theme }) => theme.colors.black};
}
input + span:after {
width: 12.5px;
height: 20px;
}
input:focus + span {
width: 35px;
height: 35px;
}
}
`
const StyledInput = styled(Input)`
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
答案 0 :(得分:2)
https://codesandbox.io/s/currying-sun-svb37
function CheckboxClick() {
if (!disableInput) {
clearInput();
}
setDisableInput(prevValue => !prevValue);
setErrors({});
}
使用默认值更新错误状态以重置错误