_blank是在按键事件中打开的新窗口 – React.js

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

_blank is opened in new window on key press event - React.js

问题

我想在我的React应用程序上按Shift + Enter时打开一个选项卡,所以我已经写好了逻辑如下:

function Apps() {
 const onKeyPressEventHandler = React.useCallback((event) => {
  if (event?.key === 'Enter' && event.shiftKey) {
   window.open('https://www.google.com/','_blank')
   return;
  }
 }, []);

 React.useEffect(() => {
  if (typeof document !== undefined) {
   document.addEventListener('keydown', onKeyPressEventHandler, false);
  }
  return () => {
   if (typeof document !== undefined) {
    document.removeEventListener('keydown', onKeyPressEventHandler, false);
   }
  };
 }, [onKeyPressEventHandler]);
 
 return (
  <div>
   HI
  </div>
 );

}

这将在按下Shift + Enter时打开一个新选项卡。如果我将window.open('https://www.google.com/','_blank')放在useEffect内部,它也能正常工作。

是否有人可以帮助我实现这个?

英文:

i want to open a tab when i press shift +enter on my react Application

so I've written the logic like this

function Apps() {
 const onKeyPressEventHandler = React.useCallback((event) =&gt; {
  if (event?.key === &#39;Enter&#39; &amp;&amp; event.shiftKey) {
   window.open(&#39;https://www.google.com/&#39;,&#39;_blank&#39;)
   return;
  }
 }, []);

 React.useEffect(() =&gt; {
  if (typeof document !== undefined) {
   document.addEventListener(&#39;keydown&#39;, onKeyPressEventHandler, false);
  }
  return () =&gt; {
   if (typeof document !== undefined) {
    document.removeEventListener(&#39;keydown&#39;, onKeyPressEventHandler, false);
   }
  };
 }, [onKeyPressEventHandler]);
 
 return (
  &lt;div&gt;
   HI
  &lt;/div&gt;
 );

}

this opens a new window, but if I keep a window.open(&#39;https://www.google.com/&#39;,&#39;_blank&#39;) inside the use effect its works fine.

can anyone help me to achieve this?

答案1

得分: 4

当使用target属性的_blank值时,通常的行为是在新标签页中打开链接。但显然,将_blank值与Shift + Enter键组合使用会强制打开新窗口(在聚焦链接并按下这两个键时也会观察到相同的行为)。

为了避免这种情况,最简单的解决方法是将window.open方法放在setTimeout中,如下所示:

setTimeout(() => window.open('https://www.google.com/', '_blank'));

似乎如果函数的调用与事件不同步,按下的键不会改变行为。

英文:

When using the _blank value for the target property, the common behaviour is to open the link in a new tab. But apparently the combination of the _blank value with the keys Shift + Enter force the opening of a new window (the same behaviour can be observed while focusing a link and pressing the two keys)

To avoid that, the easiest solution is to put the window.open method in a setTimeout like this :

setTimeout(() =&gt; window.open(&#39;https://www.google.com/&#39;, &#39;_blank&#39;));

It seems that if the call of the function is not synchronized with the event, the pressed keys won't changes the behaviour.

huangapple
  • 本文由 发表于 2023年5月10日 23:48:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220416.html
匿名

发表评论

匿名网友

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

确定