Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在react中打开url为的新选项卡_Javascript_Reactjs_Typescript_Vanilla Typescript - Fatal编程技术网

Javascript 在react中打开url为的新选项卡

Javascript 在react中打开url为的新选项卡,javascript,reactjs,typescript,vanilla-typescript,Javascript,Reactjs,Typescript,Vanilla Typescript,我正在尝试创建一个函数,用item.url打开一个新选项卡。 问题是,item.url属性是由客户端提供的,而不是由我提供的。 所以我不能确定它是以https://还是http://开头。 例如,用户可以给google.com而不是https://google.com 下面是我的代码。(此组件位于/example上) window.open(item.url,'.\u blank')}>单击 URLText只是一个样式化组件(div) 如果item.url是google.com,它将打开一

我正在尝试创建一个函数,用
item.url
打开一个新选项卡。 问题是,
item.url
属性是由客户端提供的,而不是由我提供的。 所以我不能确定它是以https://还是http://开头。 例如,用户可以给
google.com
而不是
https://google.com

下面是我的代码。(此组件位于
/example
上)

window.open(item.url,'.\u blank')}>单击
  • URLText
    只是一个样式化组件(div)

  • 如果
    item.url
    google.com
    ,它将打开一个新选项卡,其中url
    localhost:3000/example/google.com

    而不是只打开
    google.com

改用这个:

window.open((item.url.startsWith(“http://”)| | | item.url.startsWith(“https://”))?item.url:“http://“+item.url”,_blank')单击

这使用三元运算符检查传递的URL是否包含
https://
http://
,如果不包含,则将其附加到URL的开头,并将附加值或原始值返回到函数参数。

您可以使用
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>
函数handleURL(url){
if(url.includes(“http:/”)| | url.includes(“https:/”)){
返回窗口。打开(url“\u blank”)
}
window.open(`${location.protocol}/${url}`,'\u blank')
}
handleURL(item.url)}>单击
试试这种方法

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

示例fiddle-

可以假设任何使用
https://
的网站都会将HTTP重定向到https吗?不,这不安全,我也不确定。我建议使用Zam Abdul Vahid的答案。
<URLText onClick={() => window.open('//'+item.url, '_blank')}>Click</URLText>