[英]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.url
是google.com
,它使用Z572D421E5E6BCC11D11D8127272727272727272727272727272722727272.2727272727272727.11d27272715e8abc11d8abc11d8abc11d815e8abc11d8abc11d8abc11d8abc11d8abc11d8abc11d8abc11d8aporthandernement localhost:3000/example/google.com
而不是只打开google.com
。
试试这个方法。
<URLText onClick={() => window.open('//'+item.url, '_blank')}>Click</URLText>
改用这个:
<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.