Javascript 以编程方式在反应路由器的新选项卡中打开链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47789347/
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
Open link in new tab in react router programmatically
提问by Aron Karmer
I am using ReactJS for a project along with React Router (no redux) I want to programmatically open a link but on a new tab. I am aware that using
onClickNode={e => this.props.history.push('/${e.data.node.id}')}I can go to the desired link but the problem is that it gets opened in the same tab. Also there is no way to use JSX in that function and hence no possibility of adding <Link>component.
我正在将 ReactJS 与 React Router(无 redux)一起用于一个项目,我想以编程方式打开一个链接,但在一个新选项卡上。我知道使用
onClickNode={e => this.props.history.push('/${e.data.node.id}')}I 可以转到所需的链接,但问题是它在同一个选项卡中打开。此外,无法在该函数中使用 JSX,因此无法添加<Link>组件。
( I am using React Router v4)
(我使用的是 React Router v4)
回答by Aron Karmer
This https://stackoverflow.com/a/11384018/7697399answer helped me out and worked flawlessly. This could be done without the help of react-router.
这个https://stackoverflow.com/a/11384018/7697399答案帮助了我并且完美地工作。这可以在没有 react-router 帮助的情况下完成。
function openInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();
}
回答by Ares
Similar to the previous answer, but doesn't error out if the window couldn't be opened.
与上一个答案类似,但如果无法打开窗口,则不会出错。
function open(url) {
const win = window.open(url, '_blank');
if (win != null) {
win.focus();
}
}
回答by Penguin
<Link/>component from react-router-domcan be used. Using you can pass props to new tab.
<Link/>react-router-dom可以使用组件来自。使用您可以将道具传递给新标签。
<Link to='/' target="_blank">
<div> Button </div>
</Link>

