跳到主要内容

图片浏览(查看大图)

Docusaurus 中实现点击图片,查看大图的功能。

效果

尝试点击文章中的图片(查看大图)

image-20250401155130855

1. 安装依赖

npm install react-medium-image-zoom
# 或者使用 yarn
yarn add react-medium-image-zoom

2. 创建图片放大组件

在项目的 src/components 目录下创建一个全局组件,例如 ZoomableImage/index.js

/src/components/ZoomableImage/index.js
import React from 'react';
import Zoom from 'react-medium-image-zoom';
import 'react-medium-image-zoom/dist/styles.css';

const ZoomableImage = ({ src, alt, style }) => {
return (
<Zoom>
<img
src={src}
alt={alt}
style={{ cursor: 'pointer', ...style }}
/>
</Zoom>
);
};

export default ZoomableImage;

3. 注册全局组件

src/theme/MDXComponents.js 文件中注册 ZoomableImage 组件,使其在所有 Markdown 文件中生效:

/src/theme/MDXComponents.js
import React from 'react';
import ZoomableImage from '@site/src/components/ZoomableImage';

export default {
img: (props) => <ZoomableImage {...props} />,
};

4. 在 Markdown 文件中使用

在 Markdown 文件中,直接使用标准的 img 标签即可实现点击放大功能。例如:

![示例图片](../../../../static/img/example-image.png)

或者:

<img src="/img/example-image.png" alt="示例图片" />