【问题标题】:Sometimes I need to use external link with NavLink component [duplicate]有时我需要使用带有 NavLink 组件的外部链接 [重复]
【发布时间】:2023-01-14 01:45:49
【问题描述】:

我使用react-router-domNavLink组件。有时我需要在NavLink 组件中使用外部链接,但结果是:

localhost:8080/https://google.com

它有一些默认设置来区分这些情况,还是更好地编写我自己的设置?

【问题讨论】:

  • NavLink 仅用于内部链接,对于外部链接,请使用 href。
  • 我有一组数据。其中一些是外部链接,一些是指向本站的链接。这对于将来可能的灵活更改是必要的
  • 我认为您需要检查链接是内部链接还是外部链接,并决定是否应该使用 NavLink 或 ahref。

标签: javascript reactjs react-router-dom


【解决方案1】:

不失去SPA

import React, {FC, PropsWithChildren} from "react";
import {NavLink as BaseNavLink, NavLinkProps} from 'react-router-dom'

const NavLink: FC<PropsWithChildren<{to: string} & NavLinkProps>> = ({children,to, ...props}) => {
  const regExternalLink = /(https?://)?[w-~]+(.[w-~]+)+(/[w-~@:%]*)*(#[w-]*)?(?[^s]*)?/
  const isExternalLink = regExternalLink.test(to)

  return isExternalLink
    ? <a href={to}>{children}</a>
    : <BaseNavLink to={to}>{children}</BaseNavLink>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    相关资源
    最近更新 更多