[英]Next.js - How to add a <link> tag inside the <head> with literal onload attribute string value?
在 Next.js 项目中,我想在<head>
获取一些具有完全相同内容的初始 HTML:
<link href="..." rel="stylesheet" media="print" onload="this.media='all'" />
我在 Next.js 的<Head>
组件中的代码中有:
{ /* @ts-ignore */ }
<link href="..." rel="stylesheet" media="print" onload="this.media='all'" />
没有@ts-ignore
它说:
类型“DetailedHTMLProps<LinkHTMLAttributes, HTMLLinkElement>”上不存在属性“onload”。 您指的是 'onLoad' 吗? ts(2322)
如果我使用onLoad
而不是onload
我得到:
类型 'string' 不能分配给类型 '(event: SyntheticEvent<HTMLLinkElement, Event>) => void'。 ts(2322)
问题是我得到的服务器端生成的 HTML 有:
<link href="..." rel="stylesheet" media="print" />
只有在页面重新水化后,它才会更新为:
<link href="..." rel="stylesheet" media="all" onload="this.media='all'">
我在 GitHub 上发现了这个问题,但它没有帮助,因为我没有使用 Google Fonts 而是 Typography.com,所以我不能使用next-google-fonts
: https : //github.com/vercel/next .js/问题/12984
我正在考虑向该link
标签添加一个ref
并使用setAttribute
设置属性,这有望在服务器端工作,但想知道是否有更简单的方法来做到这一点。
因此,我最终在自定义_document.js
使用带有dangerouslySetInnerHTML
设置_document.js
的<style>
标记修复了此_document.js
。 总之它应该是这样的:
<link rel="preconnect" href="https://fonts.googleapis.com" crossOrigin="anonymous" />
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@400;600&family=Karla:wght@700&display=swap" as="style" />
<style dangerouslySetInnerHTML={ {
__html: `</style>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@400;600&family=Karla:wght@700&display=swap"
media="print"
onload="this.media='all';"
/>
<style>`
} }></style>
<noscript>
<link
rel="stylesheet"
type="text/css"
href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@400;600&family=Karla:wght@700&display=swap" />
</noscript>
这会生成以下输出:
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin="anonymous"/>
<link rel="preload" href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@400;600&family=Karla:wght@700&display=swap" as="style"/>
<style></style>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@400;600&family=Karla:wght@700&display=swap" media="print" onload="this.media='all';" />
<style></style>
<noscript><link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@400;600&family=Karla:wght@700&display=swap"/></noscript>
不漂亮,但比在<head>
有一个<div>
<head>
(所有浏览器都不能正确解释)。
有一个开放的 RFC来创建一个RawHTML
组件或扩展Fragment
以接受dangerouslySetInnerHTML
的RawHTML
以便这样的事情在没有黑客的情况下是可能的,但它自创建以来已经一年多了。
此外,关于这个问题的讨论也很长,还有一些似乎有效的不同解决方案(黑客)。
您可以在此处查看解决方案: https : //andorratechvalley.com/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.