useAmp
Examples
AMP 支持是我们的高级功能之一,你可以 在此处阅读有关 AMP 的更多信息。
¥AMP support is one of our advanced features, you can read more about AMP here.
要启用 AMP,请将以下配置添加到你的页面:
¥To enable AMP, add the following config to your page:
export const config = { amp: true }
amp
配置接受以下值:
¥The amp
config accepts the following values:
-
true
- 该页面将仅包含 AMP¥
true
- The page will be AMP-only -
'hybrid'
- 该页面将有两个版本,一种使用 AMP,另一种使用 HTML¥
'hybrid'
- The page will have two versions, one with AMP and another one with HTML
要了解有关 amp
配置的更多信息,请阅读以下部分。
¥To learn more about the amp
config, read the sections below.
AMP 首页
¥AMP First Page
看一下下面的例子:
¥Take a look at the following example:
export const config = { amp: true }
function About(props) {
return <h3>My AMP About Page!</h3>
}
export default About
上面的页面是仅 AMP 页面,这意味着:
¥The page above is an AMP-only page, which means:
-
该页面没有 Next.js 或 React 客户端运行时
¥The page has no Next.js or React client-side runtime
-
该页面使用 AMP 优化器 自动优化,该优化器应用与 AMP 缓存相同的转换(性能提高高达 42%)
¥The page is automatically optimized with AMP Optimizer, an optimizer that applies the same transformations as AMP caches (improves performance by up to 42%)
-
该页面具有用户可访问(优化)版本的页面和搜索引擎可索引(未优化)版本的页面
¥The page has a user-accessible (optimized) version of the page and a search-engine indexable (unoptimized) version of the page
混合 AMP 页面
¥Hybrid AMP Page
看一下下面的例子:
¥Take a look at the following example:
import { useAmp } from 'next/amp'
export const config = { amp: 'hybrid' }
function About(props) {
const isAmp = useAmp()
return (
<div>
<h3>My AMP About Page!</h3>
{isAmp ? (
<amp-img
width="300"
height="300"
src="/my-img.jpg"
alt="a cool image"
layout="responsive"
/>
) : (
<img width="300" height="300" src="/my-img.jpg" alt="a cool image" />
)}
</div>
)
}
export default About
上面的页面是一个混合 AMP 页面,这意味着:
¥The page above is a hybrid AMP page, which means:
-
页面渲染为传统 HTML(默认)和 AMP HTML(通过将
?amp=1
添加到 URL)¥The page is rendered as traditional HTML (default) and AMP HTML (by adding
?amp=1
to the URL) -
页面的 AMP 版本仅具有使用 AMP 优化器应用的有效优化,以便搜索引擎可以对其进行索引
¥The AMP version of the page only has valid optimizations applied with AMP Optimizer so that it is indexable by search-engines
该页面使用 useAmp
来区分模式,如果页面使用 AMP,则返回 true
,否则返回 false
。
¥The page uses useAmp
to differentiate between modes, it's a React Hook that returns true
if the page is using AMP, and false
otherwise.