https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx
在React中有一个textarea我想实现两个基本用例:
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使用的本机事件节点。
我注意到了错误所在。模糊事件的目标是自身
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] 删除。
我来说两句