英文:
How do I check if my input is on focus from the child component when I also need to prop drill the ref a parent component?
问题
我正在尝试根据输入是否处于焦点状态来更新样式。我了解可以在这里使用 useRef,但 inputRef 是一个可选属性,可以由父组件使用。如何从我的子组件中检查我的输入是否处于焦点状态?
import React, { RefCallback, FocusEventHandler } from "react";
import { RefCallBack } from "react-hook-form";
interface IInput {
inputRef?: RefCallBack;
onFocus?: FocusEventHandler<HTMLInputElement>;
}
const Input: React.FC<IInput> = ({ inputRef, onFocus }) => {
return (
<div>
<input type="text" ref={inputRef} onFocus={onFocus} />
</div>
);
};
export default Input;
英文:
I am trying to update styles based on if the input is on focus. I understand that I can use useRef here, but inputRef is an optional prop that can be used by a parent component. How can I check if my input is on focus from my child component shown here?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import React, { RefCallback, FocusEventHandler } from "react";
import { RefCallBack } from "react-hook-form";
interface IInput {
inputRef?: RefCallBack;
onFocus?: FocusEventHandler<HTMLInputElement>;
}
const Input: React.FC<IInput> = ({ inputRef, onFocus }) => {
return (
<div>
<input type="text" ref={inputRef} onFocus={onFocus} />
</div>
);
};
export default Input;
<!-- end snippet -->
答案1
得分: 1
你可以通过在 useEffect
中检查当前的 document.activeElement
来评估输入的焦点状态。像这样:
React.useEffect(() => {
if (document.activeElement === inputRef.current) {
// 更新不同的状态变量
}
}, [inputRef.current])
然后你可以使用该状态来动态设置父 div 的样式。
英文:
You can evaluate the input's focus state by checking for the current document.activeElement
inside a useEffect
. Something like so:
React.useEffect(() => {
if (document.activeElement === inputRef.current) {
// update a different state variable
}
}, [inputRef.current])
Then you can use that state to dynamically set styles on your parent div.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论