Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

javascript - Maintaining href "open in new tab" with an onClick handler in React

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 href on a tag gives you.

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 onClick handler on the table cell element. However there's various problems with that approach, outlined here.

TLDR: Overriding causes other problems. Solutions have various compatibility issues.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have two options here, you can make it open in a new window/tab with 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...