最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React: open link in a new tab - Stack Overflow

programmeradmin2浏览0评论

I am trying to make it so that when the user clicks my label, it opens up a new tab with the specified URL. It currently is not working. Any ideas what I am doing wrong or need to do in my method?

rerouteToGoogle= () => {
    return <Link to="google" />

}

<MediaQuery query="(min-width: 550px)">
  <div style={styles.alignText}>
  <Label color='green' basic onClick={this.rerouteToGoogle} >CSV</Label>
  </div>
</MediaQuery>

I am trying to make it so that when the user clicks my label, it opens up a new tab with the specified URL. It currently is not working. Any ideas what I am doing wrong or need to do in my method?

rerouteToGoogle= () => {
    return <Link to="google.com" />

}

<MediaQuery query="(min-width: 550px)">
  <div style={styles.alignText}>
  <Label color='green' basic onClick={this.rerouteToGoogle} >CSV</Label>
  </div>
</MediaQuery>
Share Improve this question edited Feb 27, 2019 at 22:40 GG. 21.8k14 gold badges90 silver badges132 bronze badges asked Feb 27, 2019 at 22:13 lakeIn231lakeIn231 1,2955 gold badges16 silver badges39 bronze badges 2
  • If you don't wanna use <a> then onClick={ () => window.open('www.google.com', '_blank');} – hangvirus Commented Feb 27, 2019 at 22:27
  • Hi @Jay266, could you consider accepting the answer if it helped to solve your issue? Thanks. – GG. Commented Mar 8, 2019 at 18:19
Add a comment  | 

2 Answers 2

Reset to default 10

in your case rerouteToGoogle renders a Link component. I believe what you're trying to achieve is opening the new tab link on click, not rendering it. In this case just change your function to

rerouteToGoogle= () => window.open('www.google.com', "_blank")

The purpose of <Link> is to navigate from one route to another inside your React application, e.g. from /home to /about. If you want to open another site in a new tab, then you are not navigating inside the application and so you can't use <Link>.

In your case, a classic <a href="https://google.com" target="_blank"> will work.

So, to solve what you are trying to achieve, the easiest way is to add a <a> inside your <Label>:

<MediaQuery query="(min-width: 550px)">
  <div style={styles.alignText}>
  <Label color='green' basic>
    <a href="https://google.com" target="_blank">CSV</a>
  </Label>
  </div>
</MediaQuery>
发布评论

评论列表(0)

  1. 暂无评论