失去焦点/ onBlur时反应textarea回调

贝内特水坝

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx

在React中有一个textarea我想实现两个基本用例:

  1. 当用户按下“ Escape”键时,移开焦点并重置某些状态
  2. saveToDatabase当用户在文本区域之外单击并失去焦点时执行回调()(=> onBlur
<textarea
  ref={areaRef}
  value={input}
  onChange={handleChange}
  onKeyDown={handleKeyDown}
  onBlur={handleBlur}
/>

对于第一个用例,我调用blur()目标:

const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  if (e.key === "Escape") {
    console.log("Escape clicked");
    setInput(inputForReset);
    e.currentTarget.blur();
  }
};

..但这也调用了onBlur处理程序,我实际上想在第二个用例中使用处理程序。我试图通过引用来确定事件调用者是否是textarea本身,但这不起作用:

const handleBlur = (e: React.FocusEvent<HTMLTextAreaElement>) => {
  console.log("blur");
  /**
   * Only save to database when losing focus through clicking
   * outside of the text area, not for every blur event.
   */
  if (areaRef.current && !areaRef.current.contains(e.currentTarget as Node)) {
    saveToDatabase();
  }
};

换句话说:当用户在textarea中完成编辑后,我想将某些内容保存到数据库中,但是我不知道如何区分以blur编程方式触发事件和在blur外部单击时textarea使用的本机事件节点。

皮特·皮耶普齐克(Piotr Pieprzyk)

我注意到了错误所在。模糊事件的目标是自身

areaRef === event.target

因此,您必须实现其他功能以在框外捕获点击。

import * as React from "react";
import "./styles.css";
import { useState, useRef, useEffect } from "react";

function useOutsideAlerter(
  ref: React.RefObject<HTMLTextAreaElement>,
  fun: () => void
) {
  useEffect(() => {
    function handleClickOutside(event: any) {
      if (
        ref.current &&
        !ref.current.contains(event.target) &&
        // THIS IS IMPORTANT TO CHECK
        document.activeElement === ref.current
      ) {
        fun();
      }
    }

    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [ref]);
}

export default function App() {
  const areaRef = useRef<HTMLTextAreaElement>(null);
  const [inputForReset, setInputForReset] = useState<string>("Original input");
  const [input, setInput] = useState<string>(inputForReset);

  const saveToDatabase = () => {
    console.log("save to database");
    setInputForReset(input);
    alert(input);
  };

  // OUT SIDE CLICK

  useOutsideAlerter(areaRef, saveToDatabase);

  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setInput(e.target.value);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Escape") {
      console.log("Escape clicked");
      setInput(inputForReset);
      e.currentTarget.blur();
      e.stopPropagation();
    }
  };

  // it doesnt work
  
  const handleBlur = (e: React.FocusEvent<HTMLTextAreaElement>) => {
    /**
     * Only save to database when losing focus through clicking
     * outside of the text area, not for every blur event.
     */
    console.log(event.target);
    console.log(areaRef);

    if (areaRef.current && !areaRef.current.contains(event.target)) {
      saveToDatabase();
    }
  };

  return (
    <div className="App">
      <textarea
        ref={areaRef}
        value={input}
        onChange={handleChange}
        onKeyDown={handleKeyDown}
        onBlur={handleBlur}
        className="area"
      />
      <p>Input state: {input}</p>
    </div>
  );
}

请检查我的沙箱

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章