跳到主要内容
版本:3.6.2

Docusaurus 客户端 API

Docusaurus 提供了一些客户端 API,帮助你搭建网站。

Components

<ErrorBoundary />

This component creates a React error boundary.

用它来包裹可能抛出错误的组件,并在发生这种情况时显示备用界面,而不会让整个应用崩溃。

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 用这个组件来捕捉主题布局中以及整个应用中的错误。

备注

这个组件不会捕捉构建时抛出的错误,只会保护有状态的 React 组件在客户端渲染时可能发生的错误。

Props

  • 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.
警告

The fallback prop is a callback, and not a React functional component. 你不能在这个回调中使用 React 钩子。

此可复用的 React 组件将管理您向文档头做出的所有更改。 它接受纯 HTML 标签作为参数,输出也是纯 HTML 标签,且对新手友好。 It is a wrapper around React Helmet.

示例用法:

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

嵌套或之后使用的组件将覆盖先前使用的组件:

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

会输出:

<head>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</head>

此组件链接到内部页面,同时提供强大的预加载功能。 预加载让用户在使用此组件导航之前预先加载资源。 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.

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.

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://x.com/docusaurus">X</Link>!
</p>
</div>
);

to: string

导航的目标位置。 Example: /docs/introduction.

<Link to="/courses" />
提示

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

Rendering a <Redirect> will navigate to a new location. 新位置会覆盖历史记录栈的现有位置,效果类似服务端重定向 (HTTP 3xx)。 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 implements React Router and supports its features.

<BrowserOnly/>

The <BrowserOnly> component permits to render React components only in the browser after the React app has hydrated.

提示

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 function prop returning browser-only JSX. 不会在 Node.js 中被执行。
  • 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/>

一个简单的插值组件,用于包含动态占位符的文本。

占位符会被替换为你提供的动态值和 JSX 元素(字符串、链接、样式元素等)。

Props

  • children: text containing interpolation placeholders like {placeholderName}
  • 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.io" className="my-website-class">
website
</Link>
),
}}>
{'Hello, {firstName}! How are you? Take a look at my {website}'}
</Interpolate>
);
}

<Translate/>

When localizing your site, the <Translate/> component will allow providing translation support to React components, such as your homepage. The <Translate> component supports interpolation.

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

备注

The <Translate/> props must be hardcoded strings.

Apart from the values prop used for interpolation, it is not possible to use variables, or the static extraction wouldn't work.

Props

  • children: untranslated string in the default site locale (can contain interpolation placeholders)
  • id: optional value to be used as the key in JSON translation files
  • description: optional text to help the translator
  • 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>
);
}
备注

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" />
信息

The <Translate> component supports interpolation. You can also implement string pluralization through some custom code and the translate imperative API.

Hooks

useDocusaurusContext

用于访问 Docusaurus context 的 React 钩子函数。 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>;
};

示例用法:

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>
);
};
备注

The siteConfig object only contains serializable values (values that are preserved after JSON.stringify()). 函数、正则表达式等会在客户端丢失。

useIsBrowser

Returns true when the React app has successfully hydrated in the browser.

警告

Use this hook instead of typeof windows !== 'undefined' in React rendering logic.

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.

示例用法:

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

const MyComponent = () => {
const isBrowser = useIsBrowser();
return <div>{isBrowser ? 'Client' : 'Server'}</div>;
};

useBaseUrl

React hook to prepend your site baseUrl to a string.

警告

Don't use it for regular links!

The /baseUrl/ prefix is automatically added to all absolute paths by default:

  • Markdown: [link](/my/path) will link to /baseUrl/my/path
  • React: <Link to="/my/path/">link</Link> will link to /baseUrl/my/path

选项

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} />;
};
提示

In most cases, you don't need useBaseUrl.

Prefer a require() call for assets:

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

useBaseUrlUtils

Sometimes useBaseUrl is not good enough. 这个钩子会返回与网站的 base 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

用来访问所有插件创建的 Docusaurus 全局数据的钩子。

全局数据会先按照插件名再按照插件 ID 排列。

信息

插件 ID 只在某个插件在同一个网站上被多次使用时才有用。 每个插件实例都能创建它自己的全局数据。

type GlobalData = Record<
PluginName,
Record<
PluginId, // "default" by default
any // plugin-specific data
>
>;

示例用法:

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

Inspect your site's global data at .docusaurus/globalData.json

usePluginData

访问某个特定插件实例创建的全局数据。

这是用来访问插件全局数据最方便的一个钩子,大多数时候都应该用它。

pluginId is optional if you don't use multi-instance plugins.

function usePluginData(
pluginName: string,
pluginId?: string,
options?: {failfast?: boolean},
);

示例用法:

import React from 'react';
import {usePluginData} from '@docusaurus/useGlobalData';

const MyComponent = () => {
const myPluginData = usePluginData('my-plugin');
return <div>{myPluginData.someAttribute}</div>;
};

useAllPluginInstancesData

访问某个特定插件创建的全局数据。 给定一个插件名,它会返回这个插件的所有实例的数据,按照插件 ID 排列。

function useAllPluginInstancesData(
pluginName: string,
options?: {failfast?: boolean},
);

示例用法:

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 钩子可以访问 Docusaurus 失效链接检查器 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:

  • the <Link> component will collect links for you
  • the @theme/Heading (used for Markdown headings) will collect anchors

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

示例用法:

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

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('欢迎{firstName}', {firstName: '思达'});

translate

The imperative counterpart of the <Translate> component. Also supporting placeholders interpolation.

提示

Use the imperative API for the rare cases where a component cannot be used, such as:

  • the page title metadata
  • the placeholder props of form inputs
  • 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.io/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

一个模块,导出了几个检查当前渲染环境的布尔变量。

警告

For React rendering logic, use useIsBrowser() or <BrowserOnly> instead.

示例:

import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';

if (ExecutionEnvironment.canUseDOM) {
require('lib-that-only-works-client-side');
}
字段描述
ExecutionEnvironment.canUseDOMtrue if on client/browser, false on Node.js/prerendering.
ExecutionEnvironment.canUseEventListenerstrue if on client and has window.addEventListener.
ExecutionEnvironment.canUseIntersectionObservertrue if on client and has IntersectionObserver.
ExecutionEnvironment.canUseViewporttrue if on client and has window.screen.

constants

一个模块,向客户端的主题代码提供了一些有用的常数。

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