如何检测以下输入元素当前是否集中在ReactJS渲染函数中?
<input type="text" style={searchBoxStyle} placeholder="Search"></input>
如何检测以下输入元素当前是否集中在ReactJS渲染函数中?
<input type="text" style={searchBoxStyle} placeholder="Search"></input>
只要安装了输入 node 并且有对其的引用,就可以对照document.activeElement
进行判断:
const searchInput = React.useRef(null)
if (document.activeElement === searchInput.current) {
// do something
}
return <input type="text" ref={searchInput} />
另一种方法是为输入字段中的focus
和blur
个事件添加事件侦听器:
const [focused, setFocused] = React.useState(false)
const onFocus = () => setFocused(true)
const onBlur = () => setFocused(false)
return <input type="text" onFocus={onFocus} onBlur={onBlur} />
请注意,每当 node 聚焦或模糊时,这将调用重新渲染(但这是您想要的,对吗?)