mirror of
https://github.com/d0zingcat/NotionNext.git
synced 2026-05-13 23:16:47 +00:00
feat: enhance SmartLink component for better external link handling
- support object format of href - improve URL string extraction logic - add proper type checking for href prop - ensure external links use string format
This commit is contained in:
@@ -1,23 +1,38 @@
|
||||
import Link from 'next/link'
|
||||
import { siteConfig } from '@/lib/config'
|
||||
|
||||
// 保留允许传给 <a> 的属性
|
||||
const filterDOMProps = (props) => {
|
||||
const {
|
||||
passHref,
|
||||
legacyBehavior,
|
||||
...rest
|
||||
} = props;
|
||||
return rest;
|
||||
};
|
||||
// 过滤 <a> 标签不能识别的 props
|
||||
const filterDOMProps = props => {
|
||||
const { passHref, legacyBehavior, ...rest } = props
|
||||
return rest
|
||||
}
|
||||
|
||||
const SmartLink = ({ href, children, ...rest }) => {
|
||||
const LINK = siteConfig('LINK')
|
||||
const isExternal = href.startsWith('http') && !href.startsWith(LINK)
|
||||
|
||||
// 获取 URL 字符串用于判断是否是外链
|
||||
let urlString = ''
|
||||
|
||||
if (typeof href === 'string') {
|
||||
urlString = href
|
||||
} else if (
|
||||
typeof href === 'object' &&
|
||||
href !== null &&
|
||||
typeof href.pathname === 'string'
|
||||
) {
|
||||
urlString = href.pathname
|
||||
}
|
||||
|
||||
const isExternal = urlString.startsWith('http') && !urlString.startsWith(LINK)
|
||||
|
||||
if (isExternal) {
|
||||
// 对于外部链接,必须是 string 类型
|
||||
const externalUrl =
|
||||
typeof href === 'string' ? href : new URL(href.pathname, LINK).toString()
|
||||
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
href={externalUrl}
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
{...filterDOMProps(rest)}>
|
||||
@@ -26,8 +41,9 @@ const SmartLink = ({ href, children, ...rest }) => {
|
||||
)
|
||||
}
|
||||
|
||||
// 内部链接(可为对象形式)
|
||||
return (
|
||||
<Link href={href} {...rest} >
|
||||
<Link href={href} {...rest}>
|
||||
{children}
|
||||
</Link>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user