[英]using useRef for a textbox to handle outside click not working - React functional component
am just giving a minimal code to tell about my issue am facing now我只是给出一个最小的代码来告诉我现在面临的问题
I have a textbox我有一个文本框
which is being given as这是给出的
<input type="text" ref={inputRef}/>
and和
useEffect(() => {
document.addEventListener("click", handleClickOutside, false);
return () => {
document.removeEventListener("click", handleClickOutside, false);
};
}, []);
const handleClickOutside = event => {
if (inputRef.current && !inputRef.current.contains(event.target)) {
}
};
But here am getting an error like TypeError: inputRef.current.contains is not a function但是这里出现类似TypeError: inputRef.current.contains is not a function的错误
Not sure how to check the same for input text box不知道如何检查输入文本框
Here what am trying to achieve is need to get control if user click outside the input text box Note: i had done the same for div and component, but for text box, not sure如果用户在输入文本框外部单击,则需要在这里实现控制注意:我对 div 和组件做了同样的事情,但对于文本框,不确定
Any help will be highly appreciated任何帮助将不胜感激
Below is the code snippet of a function to handle the outside click.下面是处理外部点击的 function 的代码片段。
const useOutsideClick = (ref, callback) => {
useEffect(() => {
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
callback();
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [ref, callback]);
};
Usage inside a component:组件内部的用法:
...
const inputRef = useRef(null);
useOutsideClick(inputRef, callbackToHandleOutsideClick);
return <input type="text" ref={inputRef}/>;
...
You have to use similar kind of code to make it work.您必须使用类似的代码才能使其工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.