Skip to main content
Version: 3.5.1

Docusaurus 客户端 API

¥Docusaurus Client API

Docusaurus 在客户端上提供了一些 API,可以在你构建网站时为你提供帮助。

¥Docusaurus provides some APIs on the clients that can be helpful to you when building your site.

组件

¥Components

<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.

属性

¥Props

  • fallback:返回 JSX 元素的可选渲染回调。它将接收一个具有 2 个属性的对象:error,捕获的错误,tryAgain,函数 (() => void) 回调,用于重置组件中的错误并尝试再次渲染它。如果不存在,则将渲染 @theme/Error@theme/Error 用于在布局上方封装站点的错误边界。

    ¥fallback: an optional render callback returning a JSX element. It will receive an object with 2 attributes: error, the error that was caught, and tryAgain, a function (() => void) callback to reset the error in the component and try rendering it again. If not present, @theme/Error will be rendered instead. @theme/Error is used for the error boundaries wrapping the site, above the layout.

警告

fallback prop 是一个回调,而不是 React 功能组件。你不能在此回调中使用 React hooks。

¥The fallback prop is a callback, and not a React functional component. You can't use React hooks inside this callback.

这个可重用的 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> 位于视口中时,我们使用 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:string

要导航到的目标位置。示例:/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 中运行的代码集成,因为正在访问 windowdocument 对象。

¥Use it for integrating with code that can't run in Node.js, because the window or document objects are being accessed.

属性

¥Props

  • children:render 函数 prop 返回仅浏览器的 JSX。不会在 Node.js 中执行

    ¥children: render function prop returning browser-only JSX. Will not be executed in Node.js

  • fallback(可选):JSX 在服务器 (Node.js) 上渲染,直到 React 水合完成。

    ¥fallback (optional): JSX to render on the server (Node.js) and until React hydration completes.

带有代码的示例

¥Example with code

import BrowserOnly from '@docusaurus/BrowserOnly';

const MyComponent = () => {
return (
<BrowserOnly>
{() => <span>page url = {window.location.href}</span>}
</BrowserOnly>
);
};

库示例

¥Example with a library

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...).

属性

¥Props

  • children:包含插值占位符的文本,例如 {placeholderName}

    ¥children: text containing interpolation placeholders like {placeholderName}

  • values:包含插值占位符值的对象

    ¥values: object containing interpolation placeholder 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.

属性

¥Props

  • children:默认站点区域设置中的未翻译字符串(可以包含 插值占位符

    ¥children: untranslated string in the default site locale (can contain interpolation placeholders)

  • id:用作 JSON 翻译文件中的键的可选值

    ¥id: optional value to be used as the key in JSON translation files

  • description:帮助译者的可选文本

    ¥description: optional text to help the translator

  • values:包含插值占位符值的可选对象

    ¥values: optional object containing interpolation placeholder values

示例

¥Example

src/pages/index.js
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.

钩子

¥Hooks

useDocusaurusContext

React hook 来访问 Docusaurus Context。上下文包含来自 docusaurus.config.jssiteConfig 对象和一些其他站点元数据。

¥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

    ¥Markdown: [link](/my/path) will link to /baseUrl/my/path

  • React:<Link to="/my/path/">link</Link> 将链接到 /baseUrl/my/path

    ¥React: <Link to="/my/path/">link</Link> will link to /baseUrl/my/path

选项

¥Options

type BaseUrlOptions = {
forcePrependBaseUrl: boolean;
absolute: boolean;
};

用法示例:

¥Example usage:

import React from 'react';
import useBaseUrl from '@docusaurus/useBaseUrl';

const SomeImage = () => {
const imgSrc = useBaseUrl('/img/myImage.png');
return <img src={imgSrc} />;
};
提示

在大多数情况下,你不需要 useBaseUrl

¥In most cases, you don't need useBaseUrl.

首选 require() 调用 assets

¥Prefer a require() call for assets:

<img src={require('@site/static/img/myImage.png').default} />

useBaseUrlUtils

有时 useBaseUrl 还不够好。此钩子返回与你网站的基本 URL 相关的其他实用程序。

¥Sometimes useBaseUrl is not good enough. This hook return additional utils related to your site's base URL.

  • withBaseUrl:如果你需要一次将基本 URL 添加到多个 URL,则很有用。

    ¥withBaseUrl: useful if you need to add base URLs to multiple URLs at once.

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>;
};

React hook 用于访问 Docusaurus 损坏的链接检查器 API,公开了 Docusaurus 页面报告和收集其链接和锚点的方法。

¥React hook to access the Docusaurus broken link checker APIs, exposing a way for a Docusaurus pages to report and collect their links and anchors.

警告

这是一个高级 API,大多数 Docusaurus 用户不需要直接使用。

¥This is an advanced API that most Docusaurus users don't need to use directly.

它已经内置在现有的高级组件中:

¥It is already built-in in existing high-level components:

  • <Link> 组件将为你收集链接

    ¥the <Link> component will collect links for you

  • @theme/Heading(用于 Markdown 标题)将收集锚点

    ¥the @theme/Heading (used for Markdown headings) will collect anchors

如果你实现自己的 <Heading><Link> 组件,请使用 useBrokenLinks()

¥Use useBrokenLinks() if you implement your own <Heading> or <Link> component.

使用示例:

¥Usage example:

MyHeading.js
import useBrokenLinks from '@docusaurus/useBrokenLinks';

export default function MyHeading(props) {
useBrokenLinks().collectAnchor(props.id);
return <h2 {...props} />;
}
MyLink.js
import useBrokenLinks from '@docusaurus/useBrokenLinks';

export default function MyLink(props) {
useBrokenLinks().collectLink(props.href);
return <a {...props} />;
}

函数

¥Functions

interpolate

<Interpolate> 组件的命令式对应项。

¥The imperative counterpart of the <Interpolate> component.

签名

¥Signature

// Simple string interpolation
function interpolate(text: string, values: Record<string, string>): string;

// JSX interpolation
function interpolate(
text: string,
values: Record<string, ReactNode>,
): ReactNode;

示例

¥Example

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 页元数据

    ¥the page title metadata

  • 表单输入的 placeholder 属性

    ¥the placeholder props of form inputs

  • 用于辅助功能的 aria-label 属性

    ¥the aria-label props for accessibility

签名

¥Signature

function translate(
translation: {message: string; id?: string; description?: string},
values: Record<string, string>,
): string;

示例

¥Example

src/pages/index.js
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>
);
}

模块

¥Modules

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.canUseEventListenerstrue(如果在客户端上并且具有 window.addEventListener)。
ExecutionEnvironment.canUseIntersectionObservertrue(如果在客户端上并且具有 IntersectionObserver)。
ExecutionEnvironment.canUseViewporttrue(如果在客户端上并且具有 window.screen)。

constants

向客户端主题代码公开有用常量的模块。

¥A module exposing useful constants to client-side theme code.

import {DEFAULT_PLUGIN_ID} from '@docusaurus/constants';
命名导出
DEFAULT_PLUGIN_IDdefault