React / React Hooks:每当用户离开输入字段时,我都试图使用钩子触发验证

时间:2019-06-07 04:03:17

标签: javascript reactjs react-hooks

我有一个组件设计为使用带有连接的on change功能的react钩子,以便在输入字段中预先填充客户电子邮件地址,并且如果用户单击“电子邮件选择退出”复选框,它将清除并禁用输入。现在,当用户输入新的电子邮件地址并离开输入字段时,我将尝试设计一个on change事件,该事件将触发电子邮件验证以确保其格式正确。我已经使用正则表达式编写了一个函数,其中包含要显示的错误消息,但是我不确定如何使用我现在的主要组件来实现它。我在下面包括了验证功能以及主要组件。我对钩子还很陌生,因此尝试全神贯注于如何实现所有这些逻辑已被证明有些困难,因此有关如何实现这一点的任何建议/代码示例都将提供巨大帮助

Function for Email Validation
export default function validate(values) {
  let errors = {};
  if (!values.email) {
    errors.email = 'Email address is required';
  } else if (!/\S+@\S+\.\S+/.test(values.email)) {
    errors.email = 'Email address is invalid';
  }
  return errors;
};

Main Component
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'

const CustomerDetails = ({ customer }) => {
  const { contact = {}, account = {}, site = {} } = customer || {}
  const [disableInput, setDisableInput] = React.useState(false)
  const [inputValue, setInputValue] = React.useState(contact.email)

  function clearInput() {
    setInputValue(' ')
  }

  function handleInputChange(event) {
    setInputValue(event.target.value)
  }

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


  return (
    <Container>
      <h2>{account.name}</h2>
      <Row>
        <Col span={8}>
          <H3>
            <strong>Primary Contact:</strong>
          </H3>
          <P>{contact.name}</P>
          <P>{contact.phone}</P>
        </Col>
        <Col span={8}>
          <H3>
            <strong>Service Address:</strong>
          </H3>
          <P>{site.address1}</P>
          <P>{site.address2}</P>
          <P>
            {site.city},&nbsp;{site.state}&nbsp;
            {site.postalCode}
          </P>
        </Col>
        <Col span={8}>
          <H3>
            <strong>Billing Address:</strong>
          </H3>
          <StyledMarkup>{account.billingStreet}</StyledMarkup>
          <P>
            {account.billingCity},&nbsp;{account.billingState}
            &nbsp;
            {account.billingPostalCode}
          </P>
        </Col>
      </Row>
      <br />
      <Row>
        <Col span={10}>
          <h4>
            PRIMARY CONTACT EMAIL &nbsp;
            <Tooltip
              placement="right"
              title={primaryContact}
            >
              <StyledTooltipIcon
                type="question-circle"
                theme="filled"
              />
            </Tooltip>
          </h4>
        </Col>
      </Row>
      <Row>
        <Col span={8}>
          <StyledInput
            value={inputValue}
            onChange={handleInputChange}
            disabled={disableInput}
          />
        </Col>
        <Col span={2} />
        <Col span={8}>
          <StyledCheckbox
            value={disableInput}
            onChange={CheckboxClick}
          /> EMAIL
          OPT OUT{' '}
        </Col>
      </Row>
      <br />
    </Container>
  )
}

CustomerDetails.propTypes = {
  customer: PropTypes.object
}

CustomerDetails.defaultProps = {
  customer: {}
}

export default CustomerDetails

2 个答案:

答案 0 :(得分:1)

这是您的方法:

看看是否适合您。

function validateEmail(value) {
  let errors = {};
  if (value === '') {
    errors.email = 'Email address is required';
  } else if (!/\S+@\S+\.\S+/.test(value)) {
    errors.email = 'Email address is invalid';
  }
  return errors;
};

function App() {
  const [inputValue, setInputValue] = React.useState('');
  const [errors, setErrors] = React.useState({});
  
  function onChange(e) {
    setInputValue(e.target.value);
  }
  
  function onBlur(e) {
    setErrors(validateEmail(e.target.value));
  }
  
  return(
    <div>
      <div>Fill the email input and click elsewhere to blur the field</div>
      <input onChange={onChange} onBlur={onBlur} value={inputValue} placeholder="Enter email..."/>
      {errors.email && <div>{errors.email}</div>}
    </div>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

答案 1 :(得分:0)

您现在可以在组件中使用onBlur,并在导入组件时将其与道具this.props.blur连接起来。您可以简单地使用blur

<styledInput blur={()=> this.validationFunction()}/>

现在幕后反应知道将onBlur事件的功能强制转换为映射到它的prop。