原文參考:
靜態(tài)資源存儲(chǔ) (Assets)
- 可以在頂級(jí)公共目錄下提供靜態(tài)資產(chǎn)瘩燥,如圖像等數(shù)據(jù),接下來(lái)是如何存儲(chǔ)及引用他們不皆,為了接下來(lái)的測(cè)試做一些準(zhǔn)備工作蟆技。
- 創(chuàng)建目錄
public/images
- 找一個(gè)大致 400px 乘 400px 左右的 jpg 圖片,存進(jìn)去沿侈。
- 將該文件重新命名為
profile.jpg
Image 組件
- 相較于直接試用 <img> 標(biāo)記有如下好處:
1闯第、根據(jù)不同屏幕尺寸對(duì)圖片尺寸進(jìn)行優(yōu)化,避免小設(shè)備上使用大圖的資源浪費(fèi)缀拭。
2咳短、支持Lazy loaded。
- 修改一下之前添加的
first-post.js
import Link from 'next/link';
import Image from "next/image";
export default function FirstPost() {
return <>
<h1>First Post</h1>
<h1 className="title">
Back to home <Link href="/">Back!</Link>
</h1>
<Image
src="/images/profile.jpg" // Route of the image file
height={144} // Desired size with correct aspect ratio
width={144} // Desired size with correct aspect ratio
alt="Try image"
/>
</>;
}
-
運(yùn)行后的結(jié)果蛛淋,經(jīng)過(guò)比對(duì)可以看出圖片是按照 height width 進(jìn)行了對(duì)應(yīng)的比例壓縮咙好。
Metadata 組件
-
Head
組件需要通過(guò)next/head
引入進(jìn)來(lái)。 - 做一個(gè)嘗試?yán)^續(xù)修改
first-post.js
文件給這個(gè)頁(yè)面加入 Head
import Link from 'next/link';
import Image from "next/image";
// import Head from "next/document"; 注意HEAD不要從這里引入铣鹏,如果從這里會(huì)報(bào)錯(cuò) `Cannot destructure property 'styles' of 'this.context' as it is null`
import Head from 'next/head';
export default function FirstPost() {
return <>
<Head>
<title>First Post</title>
</Head>
<h1>First Post</h1>
<h1 className="title">
Back to home <Link href="/">Back!</Link>
</h1>
<Image
src="/images/profile.jpg" // Route of the image file
height={144} // Desired size with correct aspect ratio
width={144} // Desired size with correct aspect ratio
alt="Try image"
/>
</>;
}
-
結(jié)果:
添加第三方JavaScript到頁(yè)面
- Next 框架提供了 next/script 來(lái)輔助引用外部腳本敷扫,當(dāng)然 script 標(biāo)簽依然可以工作,但是最好通過(guò)這個(gè)來(lái)引入,他可以添加一些策略控制和加載后的事件葵第,體驗(yàn)會(huì)更好绘迁。
- 繼續(xù)修改
first-post.js
文件進(jìn)行測(cè)試:
import Link from 'next/link';
import Image from "next/image";
import Script from 'next/script';
import Head from 'next/head';
export default function FirstPost() {
return <>
<Head>
<title>First Post</title>
</Head>
{/*這里是新加入的內(nèi)容*/}
<Script
src="https://connect.facebook.net/en_US/sdk.js"
strategy="lazyOnload"
onLoad={() =>
console.log(`script loaded correctly, window.FB has been populated`)
}
/>
{/*新加入內(nèi)容結(jié)束*/}
<h1>First Post</h1>
<h1 className="title">
Back to home <Link href="/">Back!</Link>
</h1>
<Image
src="/images/profile.jpg" // Route of the image file
height={144} // Desired size with correct aspect ratio
width={144} // Desired size with correct aspect ratio
alt="Try image"
/>
</>;
}
-
結(jié)果,腳本已經(jīng)加載日志已經(jīng)成功輸出卒密。
結(jié)束
接下來(lái)了解 Next.js 的布局組件