Docusaurus 客户端 API
Docusaurus 在客户端上提供了一些 API,可以在你构建网站时为你提供帮助。
英Docusaurus provides some APIs on the clients that can be helpful to you when building your site.
组件
<ErrorBoundary />
该组件创建一个 React 错误边界。
英This component creates a React error boundary.
使用它来封装可能抛出的组件,并在发生这种情况时显示回退,而不是使整个应用崩溃。
英Use it to wrap components that might throw, and display a fallback when that happens instead of crashing the whole app.
import React from 'react';
import ErrorBoundary from '@docusaurus/ErrorBoundary';
const SafeComponent = () => (
<ErrorBoundary
fallback={({error, tryAgain}) => (
<div>
<p>This component crashed because of error: {error.message}.</p>
<button onClick={tryAgain}>Try Again!</button>
</div>
)}>
<SomeDangerousComponentThatMayThrow />
</ErrorBoundary>
);
要查看其实际效果,请单击此处:
英To see it in action, click here:
Docusaurus 使用此组件来捕获主题布局以及整个应用中的错误。
英Docusaurus uses this component to catch errors within the theme's layout, and also within the entire app.
该组件不会捕获构建时错误,并且仅防止使用有状态 React 组件时可能发生的客户端渲染错误。
英This component doesn't catch build-time errors and only protects against client-side render errors that can happen when using stateful React components.
属性
fallback
: 返回 JSX 元素的可选渲染回调。 它将接收一个具有 2 个属性的对象:error
,捕获的错误,tryAgain
,函数 (() => void
) 回调,用于重置组件中的错误并尝试再次渲染它。 如果不存在,则将渲染@theme/Error
。@theme/Error
用于在布局上方封装站点的错误边界。
fallback
属性是回调,不是 React 功能组件. 你不能在此回调中使用 React hooks。
英The fallback
prop is a callback, and not a React functional component. You can't use React hooks inside this callback.
<Head/>
这个可重用的 React 组件将管理你对文档头的所有更改。 它采用纯 HTML 标签并输出纯 HTML 标签,并且适合初学者。 它是 React Helmet 的封装。
英This reusable React component will manage all of your changes to the document head. It takes plain HTML tags and outputs plain HTML tags and is beginner-friendly. It is a wrapper around React Helmet.
使用示例:
英Usage Example:
import React from 'react';
import Head from '@docusaurus/Head';
const MySEO = () => (
<Head>
<meta property="og:description" content="My custom description" />
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://mysite.com/example" />
</Head>
);
嵌套或后面的组件将覆盖重复的用法:
英Nested or latter components will override duplicate usages:
<Parent>
<Head>
<title>My Title</title>
<meta name="description" content="Helmet application" />
</Head>
<Child>
<Head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</Head>
</Child>
</Parent>
输出:
英Outputs:
<head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</head>
<Link/>
该组件可以链接到内部页面以及称为预加载的强大性能功能。 预加载用于预取资源,以便在用户使用此组件导航时获取资源。 当 <Link>
位于视口中时,我们使用 IntersectionObserver
来获取低优先级请求,然后当用户可能导航到所请求的资源时,使用 onMouseOver
事件来触发高优先级请求。
英This component enables linking to internal pages as well as a powerful performance feature called preloading. Preloading is used to prefetch resources so that the resources are fetched by the time the user navigates with this component. We use an IntersectionObserver
to fetch a low-priority request when the <Link>
is in the viewport and then use an onMouseOver
event to trigger a high-priority request when it is likely that a user will navigate to the requested resource.
该组件是 React-router 的 <Link>
组件的封装器,添加了特定于 Docusaurus 的有用增强功能。 所有 props 都会传递到 React-router 的 <Link>
组件。
英The component is a wrapper around react-router’s <Link>
component that adds useful enhancements specific to Docusaurus. All props are passed through to react-router’s <Link>
component.
外部链接也可以使用,并且自动具有这些属性: target="_blank" rel="noopener noreferrer"
。
英External links also work, and automatically have these props: target="_blank" rel="noopener noreferrer"
.
import React from 'react';
import Link from '@docusaurus/Link';
const Page = () => (
<div>
<p>
Check out my <Link to="/blog">blog</Link>!
</p>
<p>
Follow me on <Link to="https://twitter.com/docusaurus">Twitter</Link>!
</p>
</div>
);
to
:字符串
要导航到的目标位置。 例子: /docs/introduction
。
英The target location to navigate to. Example: /docs/introduction
.
<Link to="/courses" />
与普通 <a>
标签相比,更喜欢使用此组件,因为如果你使用 <Link>
,Docusaurus 会进行大量优化(例如损坏路径检测、预取、应用基本 URL...)。
英Prefer this component to vanilla <a>
tags because Docusaurus does a lot of optimizations (e.g. broken path detection, prefetching, applying base URL...) if you use <Link>
.
<Redirect/>
渲染 <Redirect>
将导航到新位置。 新位置将覆盖历史堆栈中的当前位置,就像服务器端重定向 (HTTP 3xx) 所做的那样。 你可以参考 React Router 的重定向文档 以获取有关可用属性的更多信息。
英Rendering a <Redirect>
will navigate to a new location. The new location will override the current location in the history stack like server-side redirects (HTTP 3xx) do. You can refer to React Router's Redirect documentation for more info on available props.
用法示例:
英Example usage:
import React from 'react';
import {Redirect} from '@docusaurus/router';
const Home = () => {
return <Redirect to="/docs/test" />;
};
@docusaurus/router
实现了 React Router 并支持其功能。
英@docusaurus/router
implements React Router and supports its features.
<BrowserOnly/>
<BrowserOnly>
组件允许仅在 React 应用水合后在浏览器中渲染 React 组件。
英The <BrowserOnly>
component permits to render React components only in the browser after the React app has hydrated.
使用它来与无法在 Node.js 中运行的代码集成,因为正在访问 window
或 document
对象。
英Use it for integrating with code that can't run in Node.js, because the window
or document
objects are being accessed.
属性
children
: render 函数 prop 返回仅浏览器的 JSX。 不会在 Node.js 中执行fallback
(可选): JSX 在服务器 (Node.js) 上渲染,直到 React 水合完成。
带有代码的示例
import BrowserOnly from '@docusaurus/BrowserOnly';
const MyComponent = () => {
return (
<BrowserOnly>
{() => <span>page url = {window.location.href}</span>}
</BrowserOnly>
);
};
库示例
import BrowserOnly from '@docusaurus/BrowserOnly';
const MyComponent = (props) => {
return (
<BrowserOnly fallback={<div>Loading...</div>}>
{() => {
const LibComponent = require('some-lib').LibComponent;
return <LibComponent {...props} />;
}}
</BrowserOnly>
);
};
<Interpolate/>
一个简单的插值组件,用于包含动态占位符的文本。
英A simple interpolation component for text containing dynamic placeholders.
占位符将替换为提供的动态值和你选择的 JSX 元素(字符串、链接、样式元素...)。
英The placeholders will be replaced with the provided dynamic values and JSX elements of your choice (strings, links, styled elements...).
属性
children
: 包含插值占位符的文本,例如{placeholderName}
values
: 包含插值占位符值的对象
import React from 'react';
import Link from '@docusaurus/Link';
import Interpolate from '@docusaurus/Interpolate';
export default function VisitMyWebsiteMessage() {
return (
<Interpolate
values={{
firstName: 'Sébastien',
website: (
<Link to="https://docusaurus.nodejs.cn" className="my-website-class">
website
</Link>
),
}}>
{'Hello, {firstName}! How are you? Take a look at my {website}'}
</Interpolate>
);
}
<Translate/>
当 本地化你的网站 时,<Translate/>
组件将允许提供 对 React 组件的翻译支持,例如你的主页。 <Translate>
组件支持 interpolation。
英When localizing your site, the <Translate/>
component will allow providing translation support to React components, such as your homepage. The <Translate>
component supports interpolation.
翻译字符串将使用 docusaurus write-translations
CLI 从代码中静态提取,并在 website/i18n/[locale]
中创建 code.json
翻译文件。
英The translation strings will statically extracted from your code with the docusaurus write-translations
CLI and a code.json
translation file will be created in website/i18n/[locale]
.
<Translate/>
属性 必须是硬编码字符串。
英The <Translate/>
props must be hardcoded strings.
除了用于插值的 values
属性外,它是 无法使用变量,否则静态提取将不起作用。
英Apart from the values
prop used for interpolation, it is not possible to use variables, or the static extraction wouldn't work.
属性
children
: 默认站点区域设置中的未翻译字符串(可以包含 插值占位符)id
: 用作 JSON 翻译文件中的键的可选值description
: 帮助译者的可选文本values
: 包含插值占位符值的可选对象
例子
import React from 'react';
import Layout from '@theme/Layout';
import Translate from '@docusaurus/Translate';
export default function Home() {
return (
<Layout>
<h1>
<Translate
id="homepage.title"
description="The homepage welcome message">
Welcome to my website
</Translate>
</h1>
<main>
<Translate values={{firstName: 'Sébastien'}}>
{'Welcome, {firstName}! How are you?'}
</Translate>
</main>
</Layout>
);
}
你甚至可以省略 Children 属性,并在运行 docusaurus write-translations
CLI 命令后手动在 code.json
文件中指定翻译字符串。
英You can even omit the children prop and specify a translation string in your code.json
file manually after running the docusaurus write-translations
CLI command.
<Translate id="homepage.title" />
<Translate>
组件支持插值。 你还可以通过一些自定义代码和 translate
命令式 API 来实现 字符串复数化。
英The <Translate>
component supports interpolation. You can also implement string pluralization through some custom code and the translate
imperative API.
钩子
useDocusaurusContext
React hook 来访问 Docusaurus Context。 上下文包含来自 docusaurus.config.js 的 siteConfig
对象和一些其他站点元数据。
英React hook to access Docusaurus Context. The context contains the siteConfig
object from docusaurus.config.js and some additional site metadata.
type PluginVersionInformation =
| {readonly type: 'package'; readonly version?: string}
| {readonly type: 'project'}
| {readonly type: 'local'}
| {readonly type: 'synthetic'};
type SiteMetadata = {
readonly docusaurusVersion: string;
readonly siteVersion?: string;
readonly pluginVersions: Record<string, PluginVersionInformation>;
};
type I18nLocaleConfig = {
label: string;
direction: string;
};
type I18n = {
defaultLocale: string;
locales: [string, ...string[]];
currentLocale: string;
localeConfigs: Record<string, I18nLocaleConfig>;
};
type DocusaurusContext = {
siteConfig: DocusaurusConfig;
siteMetadata: SiteMetadata;
globalData: Record<string, unknown>;
i18n: I18n;
codeTranslations: Record<string, string>;
};
使用示例:
英Usage example:
import React from 'react';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
const MyComponent = () => {
const {siteConfig, siteMetadata} = useDocusaurusContext();
return (
<div>
<h1>{siteConfig.title}</h1>
<div>{siteMetadata.siteVersion}</div>
<div>{siteMetadata.docusaurusVersion}</div>
</div>
);
};
siteConfig
对象仅包含 可序列化的值(在 JSON.stringify()
之后保留的值)。 函数、正则表达式等将在客户端丢失。
英The siteConfig
object only contains serializable values (values that are preserved after JSON.stringify()
). Functions, regexes, etc. would be lost on the client side.
useIsBrowser
当 React 应用在浏览器中成功水合时,返回 true
。
英Returns true
when the React app has successfully hydrated in the browser.
在 React 渲染逻辑中使用此钩子代替 typeof windows !== 'undefined'
。
英Use this hook instead of typeof windows !== 'undefined'
in React rendering logic.
第一个客户端渲染输出(在浏览器中)必须完全相同 作为服务器端渲染输出(Node.js)。 不遵守此规则可能会导致意外的水合行为,如 补液的危险 中所述。
英The first client-side render output (in the browser) must be exactly the same as the server-side render output (Node.js). Not following this rule can lead to unexpected hydration behaviors, as described in The Perils of Rehydration.
使用示例:
英Usage example:
import React from 'react';
import useIsBrowser from '@docusaurus/useIsBrowser';
const MyComponent = () => {
const isBrowser = useIsBrowser();
return <div>{isBrowser ? 'Client' : 'Server'}</div>;
};
useBaseUrl
React hook 将你的站点 baseUrl
添加到字符串前面。
英React hook to prepend your site baseUrl
to a string.
不要将其用于常规链接!
英Don't use it for regular links!
默认情况下,/baseUrl/
前缀会自动添加到所有 绝对路径 中:
英The /baseUrl/
prefix is automatically added to all absolute paths by default:
- Markdown:
[link](/my/path)
将链接到/baseUrl/my/path
- React:
<Link to="/my/path/">link</Link>
将链接到/baseUrl/my/path
选项
type BaseUrlOptions = {
forcePrependBaseUrl: boolean;
absolute: boolean;
};
用法示例:
import React from 'react';
import useBaseUrl from '@docusaurus/useBaseUrl';
const SomeImage = () => {
const imgSrc = useBaseUrl('/img/myImage.png');
return <img src={imgSrc} />;
};
useBaseUrlUtils
有时 useBaseUrl
还不够好。 此钩子返回与你网站的基本 URL 相关的其他实用程序。
英Sometimes useBaseUrl
is not good enough. This hook return additional utils related to your site's base URL.
withBaseUrl
: 如果你需要一次将基本 URL 添加到多个 URL,则很有用。
import React from 'react';
import {useBaseUrlUtils} from '@docusaurus/useBaseUrl';
const Component = () => {
const urls = ['/a', '/b'];
const {withBaseUrl} = useBaseUrlUtils();
const urlsWithBaseUrl = urls.map(withBaseUrl);
return <div>{/* ... */}</div>;
};
useGlobalData
React hook 用于访问由所有插件创建的 Docusaurus 全局数据。
英React hook to access Docusaurus global data created by all the plugins.
全局数据按插件名称命名,然后按插件 ID 命名。
英Global data is namespaced by plugin name then by plugin ID.
插件 ID 仅当插件在同一站点上多次使用时才有用。 每个插件实例都能够创建自己的全局数据。
英Plugin ID is only useful when a plugin is used multiple times on the same site. Each plugin instance is able to create its own global data.
type GlobalData = Record<
PluginName,
Record<
PluginId, // "default" by default
any // plugin-specific data
>
>;
使用示例:
英Usage example:
import React from 'react';
import useGlobalData from '@docusaurus/useGlobalData';
const MyComponent = () => {
const globalData = useGlobalData();
const myPluginData = globalData['my-plugin']['default'];
return <div>{myPluginData.someAttribute}</div>;
};
检查你网站的 ./docusaurus/globalData.json
全局数据
英Inspect your site's global data at ./docusaurus/globalData.json
usePluginData
访问由特定插件实例创建的全局数据。
英Access global data created by a specific plugin instance.
这是访问插件全局数据最方便的钩子,大多数时候应该使用。
英This is the most convenient hook to access plugin global data and should be used most of the time.
如果你不使用多实例插件,则 pluginId
是可选的。
英pluginId
is optional if you don't use multi-instance plugins.
function usePluginData(
pluginName: string,
pluginId?: string,
options?: {failfast?: boolean},
);
使用示例:
英Usage example:
import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';
const MyComponent = () => {
const myPluginData = usePluginData('my-plugin');
return <div>{myPluginData.someAttribute}</div>;
};
useAllPluginInstancesData
访问由特定插件创建的全局数据。 给定一个插件名称,它会按插件 ID 返回该名称的所有插件实例的数据。
英Access global data created by a specific plugin. Given a plugin name, it returns the data of all the plugins instances of that name, by plugin id.
function useAllPluginInstancesData(
pluginName: string,
options?: {failfast?: boolean},
);
使用示例:
英Usage example:
import React from 'react';
import {useAllPluginInstancesData} from '@docusaurus/useGlobalData';
const MyComponent = () => {
const allPluginInstancesData = useAllPluginInstancesData('my-plugin');
const myPluginData = allPluginInstancesData['default'];
return <div>{myPluginData.someAttribute}</div>;
};
函数
interpolate
<Interpolate>
组件的命令式对应项。
英The imperative counterpart of the <Interpolate>
component.
签名
// Simple string interpolation
function interpolate(text: string, values: Record<string, string>): string;
// JSX interpolation
function interpolate(
text: string,
values: Record<string, ReactNode>,
): ReactNode;
例子
import {interpolate} from '@docusaurus/Interpolate';
const message = interpolate('Welcome {firstName}', {firstName: 'Sébastien'});
translate
<Translate>
组件的命令式对应项。 还支持 占位符插值。
英The imperative counterpart of the <Translate>
component. Also supporting placeholders interpolation.
对于 罕见病例 和 组件无法使用 使用命令式 API,例如:
英Use the imperative API for the rare cases where a component cannot be used, such as:
title
页元数据- 表单输入的
placeholder
属性 - 用于辅助功能的
aria-label
属性
签名
function translate(
translation: {message: string; id?: string; description?: string},
values: Record<string, string>,
): string;
例子
import React from 'react';
import Layout from '@theme/Layout';
import {translate} from '@docusaurus/Translate';
export default function Home() {
return (
<Layout
title={translate({message: 'My page meta title'})}>
<img
src={'https://docusaurus.nodejs.cn/logo.png'}
aria-label={
translate(
{
message: 'The logo of site {siteName}',
// Optional
id: 'homepage.logo.ariaLabel',
description: 'The home page logo aria label',
},
{siteName: 'Docusaurus'},
)
}
/>
</Layout>
);
}
模块
ExecutionEnvironment
公开一些布尔变量来检查当前渲染环境的模块。
英A module that exposes a few boolean variables to check the current rendering environment.
对于 React 渲染逻辑,请改用 useIsBrowser()
或 <BrowserOnly>
。
英For React rendering logic, use useIsBrowser()
or <BrowserOnly>
instead.
例子:
英Example:
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
if (ExecutionEnvironment.canUseDOM) {
require('lib-that-only-works-client-side');
}
字段 | 描述 |
---|---|
ExecutionEnvironment.canUseDOM | 如果在客户端/浏览器上则为 true ,如果在 Node.js/预渲染上则为 false 。 |
ExecutionEnvironment.canUseEventListeners | true (如果在客户端上并且具有 window.addEventListener )。 |
ExecutionEnvironment.canUseIntersectionObserver | true (如果在客户端上并且具有 IntersectionObserver )。 |
ExecutionEnvironment.canUseViewport | true (如果在客户端上并且具有 window.screen )。 |
constants
向客户端主题代码公开有用常量的模块。
英A module exposing useful constants to client-side theme code.
import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants';
命名导出 | 值 |
---|---|
DEFAULT_PLUGIN_ID | default |