Javascript 在 React 中使用 onClick 处理程序维护 href“在新选项卡中打开”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45046030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Maintaining href "open in new tab" with an onClick handler in React
提问by Jose
I have an onClick (React) handler on a table cell that fires properly, however I want to maintain the "Open in a new Tab" feature that having an hrefon a tag gives you.
我在正确触发的表格单元格上有一个 onClick (React) 处理程序,但是我想保持“在新选项卡中打开”功能,该功能href在标签上为您提供。
Trying to combine both on a single element doesn't work as expected, of course:
尝试将两者结合在一个元素上并不能按预期工作,当然:
<td onClick={this.someFunction} href="someLink">
...some content
<td>
Previously I looked into having an anchor tag nested inside the table cell span the full height, so whenever the contents of the cell were right-clicked, I could "Open in a New Tab" and still keep an onClickhandler on the table cell element. However there's various problems with that approach, outlined here.
以前,我研究过在表格单元格内嵌套一个跨越整个高度的锚标记,因此每当单元格的内容被右键单击时,我都可以“在新选项卡中打开”并仍然onClick在表格单元格元素上保留一个处理程序。但是,该方法存在各种问题,概述here。
TLDR: Overriding causes other problems. Solutions have various compatibility issues.
TLDR:覆盖会导致其他问题。解决方案有各种兼容性问题。
So I ditched that approach for the one explained above. Ideas/suggestions? Is there a way to have the option "Open in a New Tab" without having to use an anchor/href?
所以我放弃了上面解释的方法。想法/建议?有没有办法让选项“在新标签页中打开”而不必使用锚点/href?
回答by gunn
You have two options here, you can make it open in a new window/tab with JS:
您在这里有两个选择,您可以使用 JS 在新窗口/选项卡中打开它:
<td onClick={()=> window.open("someLink", "_blank")}>text</td>
But a better option is to use a regular link but style it as a table cell:
但更好的选择是使用常规链接但将其设置为表格单元格:
<a style={{display: "table-cell"}} href="someLink" target="_blank">text</a>
回答by Luca Davanzo
React + TypeScriptinline util method:
React + TypeScript内联 util 方法:
const navigateToExternalUrl = (url: string, shouldOpenNewTab: boolean = true) =>
shouldOpenNewTab ? window.open(url, "_blank") : window.location.href = url;

