英文:
_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) => {
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>
);
}
this opens a new window, but if I keep a window.open('https://www.google.com/','_blank')
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(() => window.open('https://www.google.com/', '_blank'));
It seems that if the call of the function is not synchronized with the event, the pressed keys won't changes the behaviour.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论