跳到主要内容

添加悬浮按钮

本文介绍如何添加悬浮按钮支持,基于悬浮按钮可以实现返回顶部、打印文档、分享等功能。悬浮按钮的UI需要借助Ant Design,以及Docusaurus的Swizzle。

Swizzle需要使用DocItem/Layout并且使用eject模式。

添加Swizzle

npm run swizzle @docusaurus/theme-classic DocItem/Layout -- --eject
shell

生成的代码如下:

import React from 'react';
import clsx from 'clsx';
import {useWindowSize} from '@docusaurus/theme-common';
import {useDoc} from '@docusaurus/theme-common/internal';
import DocItemPaginator from '@theme/DocItem/Paginator';
import DocVersionBanner from '@theme/DocVersionBanner';
import DocVersionBadge from '@theme/DocVersionBadge';
import DocItemFooter from '@theme/DocItem/Footer';
import DocItemTOCMobile from '@theme/DocItem/TOC/Mobile';
import DocItemTOCDesktop from '@theme/DocItem/TOC/Desktop';
import DocItemContent from '@theme/DocItem/Content';
import DocBreadcrumbs from '@theme/DocBreadcrumbs';
import Unlisted from '@theme/Unlisted';
import styles from './styles.module.css';

/**
* Decide if the toc should be rendered, on mobile or desktop viewports
*/
function useDocTOC() {
const {frontMatter, toc} = useDoc();
const windowSize = useWindowSize();
const hidden = frontMatter.hide_table_of_contents;
const canRender = !hidden && toc.length > 0;
const mobile = canRender ? <DocItemTOCMobile/> : undefined;
const desktop =
canRender && (windowSize === 'desktop' || windowSize === 'ssr') ? (
<DocItemTOCDesktop/>
) : undefined;
return {
hidden,
mobile,
desktop,
};
}

export default function DocItemLayout({children}) {
const docTOC = useDocTOC();
const {
metadata: {unlisted},
} = useDoc();
return (
<div className="row">
<div className={clsx('col', !docTOC.hidden && styles.docItemCol)}>
{unlisted && <Unlisted/>}
<DocVersionBanner/>
<div className={styles.docItemContainer}>
<article>
<DocBreadcrumbs/>
<DocVersionBadge/>
{docTOC.mobile}
<DocItemContent>{children}</DocItemContent>
<DocItemFooter/>
</article>
<DocItemPaginator/>
</div>
</div>
{docTOC.desktop && <div className="col col--3">{docTOC.desktop}</div>}
</div>
);
}

tsx

添加悬浮按钮

悬浮按钮添加到{docTOC.desktop && <div className="col col--3">{docTOC.desktop}</div>}之后。本例中我们添加一个返回顶部的按钮,Ant Design中有现成的组件支持。

//...
import { FloatButton } from 'antd';
//...

//...

export default function DocItemLayout({children}) {
const docTOC = useDocTOC();
const {
metadata: {unlisted},
} = useDoc();
return (
<div className="row">
<div className={clsx('col', !docTOC.hidden && styles.docItemCol)}>
{unlisted && <Unlisted/>}
<DocVersionBanner/>
<div className={styles.docItemContainer}>
<article>
<DocBreadcrumbs/>
<DocVersionBadge/>
{docTOC.mobile}
<DocItemContent>{children}</DocItemContent>
<DocItemFooter/>
</article>
<DocItemPaginator/>
</div>
</div>
{docTOC.desktop && <div className="col col--3">{docTOC.desktop}</div>}
<FloatButton.Group shape="circle" style={{right: 24}} className="article-float-buttons">
<FloatButton.BackTop visibilityHeight={0}/>
</FloatButton.Group>
</div>
);
}



tsx

效果如下:

返回顶部
返回顶部