如何在单击<a>标签时检查是否按下了命令键

4

我在ReactJs中覆盖了anchor()标签的onClick函数,以显示加载状态。

const child: ReactElement = Children.only(children);

const childProps = {};

childProps['onClick'] = (event) => {

    if (childProps.href && child.props.target !== '_blank') {
        props.showSpinner(true);
    }

    let onClick = child.props.onClick;
    onClick && onClick();
};

return React.cloneElement(child, childProps);

然而问题在于如果用户按下shiftcommand键并点击anchor(<a>),那么用户会切换到新的标签页但是加载过程中不会显示。

因此我添加了以下条件来显示加载状态。

if (!event.shiftKey && childProps.href && child.props.target !== '_blank') {
   props.showSpinner(true);
}

这段代码处理了Shift键的按下,但我还需要处理command键的按下。 我搜索了许多帖子,它们展示了alt,shift和ctl键按下的解决方案,但没有针对command键按下的解决方案。


这个问题已经被回答了 链接在这里 - Soheb
@MSoheb 谢谢,但我有一个带有href的<a>标签,并且只能覆盖onClick。 在这种方法中,event.keyCode会返回未定义。 - Ravi Sevta
3个回答

3

您可以在按钮的onClick中检查event.metaKey的值。

    <button
      onClick={e => {
        console.log("CLICKED", e.metaKey);
      }}
    >
      Press
    </button>

在上述例子中,如果按下了命令键,则e.metaKey的值将为true

2
关于 event.metaKey 的文档:https://developer.mozilla.org/zh-CN/docs/Web/API/KeyboardEvent/metaKey - Ravi Sevta

0
据我所知,当我们使用React时,window对象不是直接可用的,您尝试过使用componentDidMount函数吗?

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接