Чтобы проверить, сфокусирован ли элемент в React, вы можете использовать следующие методы:
-
Использование свойства
document.activeElement
:const isElementFocused = () => { return document.activeElement === yourElementRef.current; };
-
Использование псевдокласса
:focus
в CSS:const isElementFocused = () => { return window.getComputedStyle(yourElementRef.current, ':focus') !== null; };
-
Использование обработчиков событий
onFocus
иonBlur
:const [isFocused, setIsFocused] = useState(false); const handleFocus = () => { setIsFocused(true); }; const handleBlur = () => { setIsFocused(false); }; return ( <input ref={yourElementRef} onFocus={handleFocus} onBlur={handleBlur} /> );