javascript React Router - 在新选项卡上打开链接并重定向到主页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51434254/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:32:50  来源:igfitidea点击:

React Router - Open Link on new Tab and Redirect to Home Page

javascriptreactjsreact-router

提问by Jonca33

Using React Router 4.2

使用 React Router 4.2

My attempt is to opena new tab upon clicking on a navigation link and at the same time be redirectedto the site homepage.

我的尝试是在单击导航链接时打开一个新选项卡,同时重定向到站点主页。

ie: Navigation bar: clicking on Policies

即:导航栏:点击政策

enter image description here

在此处输入图片说明

Even though the code bellow behaves as the requirements above: Is this the advisable way to go about it? Aiming to learn best practices here on Routes.js.

即使下面的代码符合上述要求:这是实现它的可取方法吗?旨在在 Routes.js 上学习最佳实践。

 //Routes.js
 import HandbookDoc from './policies.pdf'
 ...

 <Route 
   path="/registration/policies" 
   component={() => window.open(`${HandbookDoc}`,'_blank').then(window.location= '/')} 
 />

....

....

 //Navigation.js (using react-router-bootstrap)
  <NavDropdown eventKey={3} id="formId" title="Registration">
     <LinkContainer to="/registration/financial-aid">
        <MenuItem eventKey={3.1}>Financial Aid</MenuItem>
      </LinkContainer>
      <LinkContainer to="/registration/policies">
        <MenuItem eventKey={3.2}>Policies</MenuItem>
      </LinkContainer>
  </NavDropdown>

回答by Hymanyef

You don't need to create a new route for the thing you are trying to achieve. You could add an onClickhandler to the MenuItemlike this:

您无需为要实现的目标创建新路线。你可以像这样添加一个onClick处理程序MenuItem

  <NavDropdown eventKey={3} id="formId" title="Registration">
     <LinkContainer to="/registration/financial-aid">
        <MenuItem eventKey={3.1}>Financial Aid</MenuItem>
      </LinkContainer>
      <LinkContainer 
        to="/">
        <MenuItem onClick={this.handlePoliciesClick} eventKey={3.2}>Policies</MenuItem>
      </LinkContainer>
  </NavDropdown>

And then in same component add the handler:

然后在同一个组件中添加处理程序:

handlePoliciesClick = () => {
  window.open(HandbookDoc, '_blank');
}

Remember to import your HandbookDoc.

记得导入你的HandbookDoc.