Как сделать onEndEditing на входе ReactJs - PullRequest
0 голосов
/ 19 марта 2020

Я пытаюсь создать функцию endEditing для reactJs, но у меня проблема при использовании перехватчиков событий, она вызывает событие focusout, но вызывает функции, объявленные во всех входах, а не только в вход, который был выбран. Я попытался сделать это, чтобы активировать функцию всех входов, если я оставлю только один.

src / components. js


export default function Input({
  inputRef,
  inputType,
  placeholder,
  functionOnEndingChange,
  functionUpdatedValueRef,
}) {
  useEventListener('focusout', functionOnEndingChange);

  return (
    <InputText
      type={inputType}
      ref={inputRef}
      placeholder={placeholder}
      onChange={text => functionUpdatedValueRef(text.target.value)}
    />
  );
}

Input.propTypes = {
  functionUpdatedValueRef: PropTypes.func,
  functionOnEndingChange: PropTypes.func,
  inputType: PropTypes.string,
  inputRef: PropTypes.func,
  placeholder: PropTypes.string,
};
Input.defaultProps = {
  functionUpdatedValueRef: () => {},
  functionOnEndingChange: () => null,
  inputType: 'text',
  inputRef: () => {},
  placeholder: 'placeholder input:',
};

src / utils / hooksEvent. js

export default function useEventListener(eventName, handler, element = window) {
  // Create a ref that stores handler
  const savedHandler = useRef();

  // Update ref.current value if handler changes.
  // This allows our effect below to always get latest handler ...
  // ... without us needing to pass it in effect deps array ...
  // ... and potentially cause effect to re-run every render.
  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);

  useEffect(
    () => {
      // Make sure element supports addEventListener
      // On
      const isSupported = element && element.addEventListener;
      if (!isSupported) return;

      // Create event listener that calls handler function stored in ref
      const eventListener = event => savedHandler.current(event);

      // Add event listener
      element.addEventListener(eventName, eventListener);

      // Remove event listener on cleanup
      return () => {
        element.removeEventListener(eventName, eventListener);
      };
    },
    [eventName, element] // Re-run if eventName or element changes
  );
}

src / page / testeInput. js

<Column flex={1}>
  <AreaInput>
    <LabelText name="EMAIL" />
    <Input
      inputRef={inputEmailRef}
      inputType="email"
      placeholder="example@example.com"
      functionUpdatedValueRef={text => setEmailState(text)}
      functionOnEndingChange={() =>
        verifyEmail('email', emailState)
      }
    />
  </AreaInput>
<AreaInput>
    <LabelText name="EMAIL2" />
    <Input
      inputRef={inputEmailRef2}
      inputType="email2"
      placeholder="example@example.com"
      functionUpdatedValueRef={text => setEmailState(text)}
      functionOnEndingChange={() =>
        verifyEmailTwo('email2', emailState)
      }
    />
  </AreaInput>
</Column>

, нажав на один из входов и оставив фокус, он активирует обе функции

1 Ответ

0 голосов
/ 20 марта 2020

Ответ на проблему прост: использование onBlur решает проблему https://reactjs.org/docs/events.html#focus -events

, тогда компонент может выглядеть следующим образом

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import {
  AreaInputIcon,
  AreaInput,
  Input,
  InputFormMask,
  AreaIcon,
  IconUser,
  IconOpenEyes,
  IconClosedEyes,
} from './styles';
import { useEventListener } from '../../utils';

export default function InputIcon({
  iconName,
  button,
  functionOnClick,
  error,
  disabled,
  inputRef,
  type,
  functionUpdatedValueRef,
  functionOnEndingChange,
  placeholder,
  inputMask,
}) {
  // useEventListener('focusout', functionOnEndingChange);
  function choseIcons(nameParam) {
    switch (nameParam) {
      case 'user':
        return <IconUser />;
      case 'passwordOpen':
        return <IconOpenEyes />;
      case 'passwordClosed':
        return <IconClosedEyes />;
      default:
        return <IconUser />;
    }
  }
  return (
    <AreaInputIcon>
      <AreaInput error={error}>
        {type !== 'mask' ? (
          <Input
            ref={inputRef}
            placeholder={placeholder}
            onChange={text => functionUpdatedValueRef(text.target.value)}
            onBlur={functionOnEndingChange}
          />
        ) : (
          <InputFormMask
            ref={inputRef}
            mask={inputMask}
            placeholder={placeholder}
            onChange={text => functionUpdatedValueRef(text.target.value)}
            onBlur={functionOnEndingChange}
          />
        )}
      </AreaInput>
      <AreaIcon
        button={button}
        onClick={functionOnClick}
        error={error}
        disabled={disabled}
      >
        {choseIcons(iconName)}
      </AreaIcon>
    </AreaInputIcon>
  );
}
InputIcon.propTypes = {
  iconName: PropTypes.string,
  button: PropTypes.bool,
  functionOnClick: PropTypes.func,
  functionUpdatedValueRef: PropTypes.func,
  error: PropTypes.bool,
  type: PropTypes.string,
  disabled: PropTypes.bool,
  inputRef: PropTypes.func,
  functionOnEndingChange: PropTypes.func,
  inputMask: PropTypes.string,
  placeholder: PropTypes.string,
};
InputIcon.defaultProps = {
  iconName: 'user',
  button: false,
  functionOnClick: () => {},
  functionUpdatedValueRef: () => {},
  error: false,
  type: 'common',
  disabled: true,
  inputRef: () => {},
  functionOnEndingChange: () => {},
  inputMask: '99/99/99',
  placeholder: 'palceholder input:',
};
...