如果不存在 http 或 https,反应中的外部 link 将附加本地主机

External link in react is being appended with localhost if no http or https present

我现在正在使用此代码从生成的 URL 打开外部 link:

如果不存在 http 或 https,则反应中的外部 link 将附加本地主机

  <a href={url} target={'_blank'} rel="noopener noreferrer external">
        {url}
  </a>

如果 url 中存在 http 或 https,则工作正常,但如果存在 none,则它将被重定向到 http://localhost:3000/${url}

有没有办法在 React 中忽略这个设置(Create React App)

添加这个条件如果url为空则不会重定向

{url && <a href={url} target={'_blank'} rel="noopener noreferrer external">
    {url}</a>}

这和react完全没有关系,这是基于浏览器如何理解urls。 url 有 4 种类型:

http://yourdomain.com/images/example.png:(这对你来说很好,因为它是绝对的url,浏览器会按原样打开它)

//yourdomain.com/images/example.png(这也和上一个一样,对你来说会很好,除了这里的架构是相对于当前主机的,如果你的网站是 https 它将打开 https 否则它会打开HTTP)

您遇到以下两个 url 的问题,那是因为它们相对于当前主机工作,在您的情况下,您的网站似乎在 http://localhost:3000

/images/example.png(相对于文档根目录)

images/example.png(相对路径)

现在如果你想将相对 urls 转换为相对于另一个主机,使用 URL constructor 这样的

const baseOfAnotherHost = 'https://someotherdomain.com'
// can also work with relative urls like 'doc/sign/' or '/doc/sign'
const relativeOrAbsoluteURL = 'https://www.someotherdomain.com/doc'
const absoulteUrl = new URL(relativeOrAbsoluteURL,baseOfAnotherHost).href
<a href={absoulteUrl} target={'_blank'} rel="noopener noreferrer external">
    {absoulteUrl}</a>