Иметь вход с подтверждением для электронной почты, пытаясь очистить сообщение об ошибке и затемнить ввод при нажатии флажка - PullRequest
1 голос
/ 08 июня 2019

Я создал компонент, используя 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 &nbsp;
          </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

1 Ответ

2 голосов
/ 08 июня 2019

https://codesandbox.io/s/currying-sun-svb37

function CheckboxClick() {
if (!disableInput) {
  clearInput();
}
setDisableInput(prevValue => !prevValue);
setErrors({});

}

обновить состояние ошибки значением по умолчанию для сброса ошибки

...