繁体   English   中英

在反应中使用 url 打开新标签

[英]Opening new tab with url in react

我正在尝试制作 function 以使用item.url打开新标签。 问题是, item.url属性是由客户给出的,而不是由我给出的。 所以我无法确定它是否以https://http:// 例如,用户可以给出google.com而不是https://google.com

下面是我的代码。 (这个组件在/example上)

<URLText onClick={() => window.open(item.url, '_blank')}>Click</URLText>
  • URLText只是一个样式化的组件(div)。

  • 如果item.urlgoogle.com ,它使用Z572D421E5E6BCC11D11D8127272727272727272727272727272722727272.2727272727272727.11d27272715e8abc11d8abc11d8abc11d815e8abc11d8abc11d8abc11d8abc11d8abc11d8abc11d8abc11d8aporthandernement localhost:3000/example/google.com
    而不是只打开google.com

试试这个方法。

<URLText onClick={() => window.open('//'+item.url, '_blank')}>Click</URLText>

小提琴样本 - https://jsfiddle.net/pecu0szq/12/

改用这个:

<URLText onClick={() => window.open((item.url.startsWith("http://") || item.url.startsWith("https://")) ? item.url : "http://" + item.url, '_blank')}>Click</URLText>

This uses the ternary operator to check if the passed URL contains https:// or http:// , appends it to the beginning of the URL if it doesn't, and returns the appended or original value to the function parameter.

您可以使用window.location.protocol获取当前 url 的协议。

function handleURL(url) {
   if (url.includes("http://") || url.includes("https://")) {
      return window.open(url, '_blank')
   }

   window.open(`${location.protocol}//${url}`, '_blank')
}

<URLText onClick={() => handleURL(item.url)}>Click</URLText>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM