1、项目准备
确保已经有一个 Next.js 项目。如果没有,可以通过以下命令创建一个新的 Next.js 项目:
npx create-next-app@latest my-nextjs-toc
cd my-nextjs-toc
2、创建自定义的 HTML 解析和 TOC 生成函数
在项目中创建一个新的文件,如 utils.js,并在其中定义一个用于解析 HTML 文本和生成目录的函数:
// utils.js
export const generateTOC = (htmlString) => {
const toc = [];
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
// 查找所有 h1-h6 元素
doc.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach((header) => {
const level = parseInt(header.tagName[1], 10);
let id = header.id;
if (!id) {
// 如果没有 id,根据标题文本生成 id
id = header.textContent.trim().replace(/\s+/g, '-').toLowerCase();
header.id = id; // 给原始元素添加 id
}
toc.push({
id,
text: header.textContent.trim(),
level,
});
});
return { toc, htmlString: doc.body.innerHTML };
};
3、创建平滑滚动函数
在同一个文件(utils.js)中,添加一个用于平滑滚动并向上偏移 10px 的函数:
export const scrollToId = (id) => {
const element = document.getElementById(id);
if (element) {
const top = element.getBoundingClientRect().top + window.pageYOffset - 10;
window.scrollTo({
top,
behavior: 'smooth',
});
}
};
4、创建目录组件
接下来,在组件目录中创建一个 TOC.js 文件,定义目录组件:
// components/TOC.js
import React from 'react';
import { scrollToId } from '../utils';
const TOC = ({ toc }) => {
return (
<ul>
{toc.map((item, index) => (
<li key={index} style={{ marginLeft: (item.level - 1) * 20 + 'px' }}>
<a href={`#${item.id}`} onClick={(e) => {
e.preventDefault();
scrollToId(item.id);
}}>
{item.text}
</a>
</li>
))}
</ul>
);
};
export default TOC;
5、整合到 Next.js 页面
在你的 Next.js 页面文件中(例如 pages/index.js),你可以使用上述函数和组件:
// pages/index.js
import React from 'react';
import TOC from '../components/TOC';
import { generateTOC } from '../utils';
const HomePage = () => {
const htmlContent = `
<h1 id="introduction">Introduction to 3D Printing</h1>
<p>3D printing, also known as additive manufacturing, is a process of creating three-dimensional objects from a digital file.</p>
<h2 id="history">History of 3D Printing</h2>
<p>The first 3D printing technology was developed in the 1980s, known as stereolithography.</p>
<h3 id="early-years">Early Years</h3>
<p>In the early years, 3D printing was mainly used for rapid prototyping.</p>
<h3 id="modern-era">Modern Era</h3>
<p>Today, 3D printing is used in various industries, including healthcare, aerospace, and automotive.</p>
<h2 id="technologies">3D Printing Technologies</h2>
<p>There are several types of 3D printing technologies, including:</p>
<ul>
<li><strong>FDM (Fused Deposition Modeling):</strong> The most common 3D printing technology, used by desktop 3D printers.</li>
<li><strong>SLA (Stereolithography):</strong> A 3D printing process that uses a laser to cure liquid resin into hardened plastic.</li>
<li><strong>SLM (Selective Laser Melting):</strong> A metal 3D printing technology that uses a laser to melt metal powder into solid parts.</li>
</ul>
<h3 id="fdm">FDM</h3>
<p>FDM is widely used in home 3D printers due to its affordability and ease of use.</p>
<h3 id="sla">SLA</h3>
<p>SLA is known for producing high-resolution parts, making it ideal for creating detailed prototypes.</p>
<h3 id="slm">SLM</h3>
<p>SLM is primarily used in the aerospace and medical industries to produce strong and complex metal parts.</p>
<h2 id="applications">Applications of 3D Printing</h2>
<p>3D printing has numerous applications, ranging from prototyping to end-use production.</p>
<h3 id="healthcare">Healthcare</h3>
<p>In healthcare, 3D printing is used to create custom prosthetics, implants, and even organs.</p>
<h3 id="aerospace">Aerospace</h3>
<p>The aerospace industry uses 3D printing to produce lightweight and strong parts, reducing the weight of aircraft.</p>
<h3 id="automotive">Automotive</h3>
<p>3D printing is used in the automotive industry to create prototypes, custom parts, and even entire vehicles.</p>
<h2 id="conclusion">Conclusion</h2>
<p>3D printing is a revolutionary technology that is transforming how products are designed, prototyped, and manufactured.</p>
<h3 id="future">The Future of 3D Printing</h3>
<p>As 3D printing technology continues to evolve, it will play an increasingly important role in various industries worldwide.</p>
<figure class="wp-block-image size-large">
<img src="https://example.com/3d-printing.jpg" alt="3D printing in action" />
<figcaption>A 3D printer creating a complex part</figcaption>
</figure>
`;
const { toc, htmlString } = generateTOC(htmlContent);
return (
<div>
<TOC toc={toc} />
<div dangerouslySetInnerHTML={{ __html: htmlString }} />
</div>
);
};
export default HomePage;
6、启动项目
确保所有代码都正确编写后,运行以下命令启动你的 Next.js 项目:
npm run dev
在浏览器中访问 http://localhost:3000,会看到生成的目录,点击目录项可以平滑滚动到对应的标题位置,并且滚动位置会向上偏移 10px。