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?

huangapple go评论112阅读模式
英文:

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 是一个可选属性,可以由父组件使用。如何从我的子组件中检查我的输入是否处于焦点状态?

  1. import React, { RefCallback, FocusEventHandler } from "react";
  2. import { RefCallBack } from "react-hook-form";
  3. interface IInput {
  4. inputRef?: RefCallBack;
  5. onFocus?: FocusEventHandler<HTMLInputElement>;
  6. }
  7. const Input: React.FC<IInput> = ({ inputRef, onFocus }) => {
  8. return (
  9. <div>
  10. <input type="text" ref={inputRef} onFocus={onFocus} />
  11. </div>
  12. );
  13. };
  14. 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 -->

  1. import React, { RefCallback, FocusEventHandler } from &quot;react&quot;;
  2. import { RefCallBack } from &quot;react-hook-form&quot;;
  3. interface IInput {
  4. inputRef?: RefCallBack;
  5. onFocus?: FocusEventHandler&lt;HTMLInputElement&gt;;
  6. }
  7. const Input: React.FC&lt;IInput&gt; = ({ inputRef, onFocus }) =&gt; {
  8. return (
  9. &lt;div&gt;
  10. &lt;input type=&quot;text&quot; ref={inputRef} onFocus={onFocus} /&gt;
  11. &lt;/div&gt;
  12. );
  13. };
  14. export default Input;

<!-- end snippet -->

答案1

得分: 1

你可以通过在 useEffect 中检查当前的 document.activeElement 来评估输入的焦点状态。像这样:

  1. React.useEffect(() => {
  2. if (document.activeElement === inputRef.current) {
  3. // 更新不同的状态变量
  4. }
  5. }, [inputRef.current])

然后你可以使用该状态来动态设置父 div 的样式。

英文:

You can evaluate the input's focus state by checking for the current document.activeElement inside a useEffect. Something like so:

  1. React.useEffect(() =&gt; {
  2. if (document.activeElement === inputRef.current) {
  3. // update a different state variable
  4. }
  5. }, [inputRef.current])

Then you can use that state to dynamically set styles on your parent div.

huangapple
  • 本文由 发表于 2023年6月22日 04:46:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定