状态在事件侦听器之间未按预期更新

时间:2019-03-15 15:10:56

标签: javascript reactjs lodash react-hooks

我有两个输入。

Email Address

First Name

在初始加载时,名字被隐藏了。

单击电子邮件地址输入,将隐藏一个div并显示名字输入。 还将在输入上方隐藏一个div,输入将填充该空间。

现在,我要寻找的功能是在用户单击电子邮件地址输入后,然后在用户单击名字时,名字不应该消失并且div返回。

为此,目前,我在onBlur事件监听器上添加了lodash的反跳延迟,以等待用户是否专注于名字输入。

我有一个状态变量onBlurWait,该变量默认为false,并且当用户关注名字输入时会更新为true

将焦点放在名字输入上,调用onBlur事件侦听器以检查onBlurWait状态的值。目前,此侦听器仅返回console.logonBlurWait

电子邮件地址输入中的onBlur似乎在名字输入onFocus之前被调用。因此,看来onBlurWait状态没有得到更新,因此console.log事件监听器中的onBlur将返回false。

这里有一个CodeSandbox,可以帮助您使用它,因此您可以希望理解上面我所指的内容。

下面是我的组件

import React, { useState } from "react";
import ReactDOM from "react-dom";
import _ from "lodash";

import InputControl from "./InputControl";

import "./styles.css";

const App = () => {
  const [hideContent, setHideContent] = useState(false);
  const [emailSignUpRef, setEmailSignUpRef] = useState(null);
  const [firstNameSignUpRef, setFirstNameEmailSignUpRef] = useState(null);
  const [onBlurWait, setOnBlurWait] = useState(false);

  let registerEmailInput = null;
  let firstNameInput = null;

  // If you click on email address then on first name, I would expect the console.log below to return true
  // due to when a user focuses on the first name input the handleInputFocus function gets called
  // inside that function, setOnBlurWait(true); is ran updating the value of onBlurWait to true
  // But it seems like it has not actually been updated
  // Now when you click on email address to first name, back to email address and first name again, the console log now returns true?
  const waitOnUpdateState = _.debounce(() => console.log(onBlurWait), 2000);
  const hideContentAfterState = _.debounce(
    () =>
      setHideContent(
        emailSignUpRef.length > 0 || firstNameSignUpRef.length > 0 || onBlurWait
      ),
    2000
  );

  const handleOnFocus = event => {
    setEmailSignUpRef(registerEmailInput.value);
    setFirstNameEmailSignUpRef(firstNameInput.value);
    setHideContent(true);
  };

  const handleOnInput = () => {
    setEmailSignUpRef(registerEmailInput.value);
    setFirstNameEmailSignUpRef(firstNameInput.value);
  };

  const handleInputFocus = () => {
    console.log("clicked on first name, onBlurWait should be set as true");
    setOnBlurWait(true);
  };

  const handleOnBlur = () => {
    console.log("clicked away from email address");
    // waitOnUpdateState is just a test function to return a console log, hideContentAfterState is what is going to be used
    waitOnUpdateState();
    hideContentAfterState();
  };

  return (
    <div className="App">
      <div className={hideContent ? "hidden" : "visible"} />
      <InputControl
        autoComplete="off"
        refProp={input => {
          registerEmailInput = input;
        }}
        onInput={handleOnInput}
        onFocus={handleOnFocus}
        onBlur={handleOnBlur}
        type="text"
        name="emailAddressRegister"
        placeholder="Email address"
        label="Email Address"
      />
      <InputControl
        className={
          !hideContent ? "InputControl--hidden" : "InputControl--visible"
        }
        autoComplete="off"
        refProp={input => {
          firstNameInput = input;
        }}
        onInput={handleOnInput}
        onFocus={handleInputFocus}
        type="text"
        name="firstName"
        placeholder="First Name"
        label="First Name"
      />
      <input type="submit" value="Submit" />
    </div>
  );
};

export default App;

1 个答案:

答案 0 :(得分:1)

考虑简化它,您正在考虑过度。

onFocusonBlur都收到relatedTarget作为其SyntheticEvent中的属性之一。对于onBlurrelatedTargettarget的DOM元素for which the focus is leaving

您可以做的是处理blur事件,并将事件的relatedTarget属性与输入引用进行比较。然后,您将能够确定焦点是要留在页面上的另一个表单元素还是其他DOM元素。