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

|▌冷眼眸甩不掉的悲伤 提交于 2020-07-06 20:37:30

问题


Using React Router 4.2

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

ie: Navigation bar: clicking on Policies

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
 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>

回答1:


You don't need to create a new route for the thing you are trying to achieve. You could add an onClick handler to the MenuItem like this:

  <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.



来源:https://stackoverflow.com/questions/51434254/react-router-open-link-on-new-tab-and-redirect-to-home-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!