检测输入元素是否在 ReactJS 中获得焦点 [英] Detect whether input element is focused within ReactJS

查看:66
本文介绍了检测输入元素是否在 ReactJS 中获得焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测诸如以下的输入元素当前是否在 ReactJS 渲染函数中获得焦点?

How can I detect whether an input element such as the following is currently focused within a ReactJS render function?

<input type="text" style={searchBoxStyle} placeholder="Search"></input>   

推荐答案

只要输入节点被挂载并且有对它的引用,你就可以检查document.activeElement:

You can check against document.activeElement as long as the input node is mounted and there is a reference to it:

const searchInput = React.useRef(null)

if (document.activeElement === searchInput.current) {
  // do something
}

return <input type="text" ref={searchInput} />

另一种方法是为输入字段内的 focusblur 事件添加事件侦听器:

Another way would be to add event listeners for the focus and blur events inside the input field:

const [focused, setFocused] = React.useState(false)
const onFocus = () => setFocused(true)
const onBlur = () => setFocused(false)

return <input type="text" onFocus={onFocus} onBlur={onBlur} />

请注意,每次节点聚焦或模糊时,这都会调用重新渲染(但这正是您想要的,对吧?)

Note that this will call a re-render each time the node is focused or blurred (but this is what you want, right?)

这篇关于检测输入元素是否在 ReactJS 中获得焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆