gpt4 book ai didi

javascript - Next.js - 如何在 内添加带有文字 onload 属性字符串值的 标记?

转载 作者:行者123 更新时间:2023-12-04 17:24:53 31 4
gpt4 key购买 nike

在 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它说:

Property 'onload' does not exist on type 'DetailedHTMLProps<LinkHTMLAttributes, HTMLLinkElement>'. Did you mean 'onLoad'? ts(2322)


如果我使用 onLoad而不是 onload我得到:

Type 'string' is not assignable to type '(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 字体而是 Typography.com,所以我不能使用 next-google-fonts : https://github.com/vercel/next.js/issues/12984
我正在考虑添加 ref到那个 link使用 setAttribute 标记和设置属性,这也有望在服务器端工作,但想知道是否有更简单的方法来做到这一点。

最佳答案

所以我最终使用 <style> 解决了这个问题。带有 dangerouslySetInnerHTML 的标签在 custom _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&amp;family=Karla:wght@700&amp;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&amp;family=Karla:wght@700&amp;display=swap"/></noscript>
不漂亮,但比拥有 <div> 更好里面 <head> (并非所有浏览器都正确解释)。
有一个 open RFC创建 RawHTML组件或扩展 Fragment接受 dangerouslySetInnerHTML所以这样的事情在没有黑客的情况下是可能的,但它已经创建了一年多。
还有 quite a long discussion about this以及一些似乎可行的不同解决方案(黑客)。
您可以在此处查看解决方案: https://andorratechvalley.com/

关于javascript - Next.js - 如何在 <head> 内添加带有文字 onload 属性字符串值的 <link> 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64121456/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com