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评论69阅读模式
英文:

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 &quot;react&quot;;
import { RefCallBack } from &quot;react-hook-form&quot;;

interface IInput {
  inputRef?: RefCallBack;
  onFocus?: FocusEventHandler&lt;HTMLInputElement&gt;;
}
const Input: React.FC&lt;IInput&gt; = ({ inputRef, onFocus }) =&gt; {
  return (
    &lt;div&gt;
      &lt;input type=&quot;text&quot; ref={inputRef} onFocus={onFocus} /&gt;
    &lt;/div&gt;
  );
};

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(() =&gt; {
  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.

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:

确定