[英]onBlur doesn't fire when onClick is triggered programmatically
I'm working with a React component:我正在使用 React 组件:
<div
ref={tooltipContainer}
onClick={() => {
console.log('onclick');
}}
onBlur={() => {
console.log('onblur');
}}
>
// Hello
</div>
In my componentDidMount hook I'm triggering a click on the div which works as expected (shows the console log).在我的 componentDidMount 钩子中,我触发了对 div 的点击,它按预期工作(显示控制台日志)。
useEffect(() => {
if (someCondition) {
tooltipContainer.current.click();
}
}, []);
However when I click anywhere else on the page the onBlur
event isn't triggered.但是,当我单击页面上的任何其他地方时,不会触发
onBlur
事件。 Shouldn't it since I programmatically clicked on the same element?不应该是因为我以编程方式点击了同一个元素吗?
Apparently div
doesn't have onBlur
event handler if there is no contentEditable
or tabindex=0
provided.如果没有提供
contentEditable
或tabindex=0
显然div
没有onBlur
事件处理程序。 But even with those, you'll still need some tweaks.但即使有这些,你仍然需要一些调整。
You want to make div
focused on click, and clicking on it programmatically doesn't make it focused, so you'll have to add tooltipContainer.current.focus()
under click()
您想让
div
专注于点击,而以编程方式点击它并不会使其聚焦,因此您必须在click()
下添加tooltipContainer.current.focus()
click()
const myDiv = document.querySelector("#myDiv"); myDiv.click(); myDiv.focus();
#myDiv { border: 1px solid green; padding: 1rem; }
<div tabindex="0" onblur="alert('Hello!');" id="myDiv" >Click outside of the box!</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.