react实现博客文章概要
实现博客文章概要的几种方法
使用字符串截取 通过截取文章内容的前N个字符作为概要,适用于纯文本内容。注意处理中文字符和截断位置。
function getSummary(content, length = 100) {
return content.length > length
? content.substring(0, length) + '...'
: content;
}
正则表达式提取首段 匹配文章的第一个段落作为概要,保留段落结构。
function getFirstParagraph(content) {
const match = content.match(/<p>(.*?)<\/p>|^[^\n]+/);
return match ? match[0] : content;
}
使用第三方库
如react-truncate组件可以智能处理HTML内容和响应式截断。
import Truncate from 'react-truncate';
<Truncate lines={3} ellipsis={<span>...</span>}>
{articleContent}
</Truncate>
服务端生成概要 在Node.js后端处理更高效,避免客户端计算开销。
// 服务端中间件示例
app.use((req, res, next) => {
if (req.body.content) {
req.body.excerpt = generateExcerpt(req.body.content);
}
next();
});
进阶实现方案
关键词提取算法 结合TF-IDF等算法提取核心句子,需要自然语言处理库支持。
import { analyze } from 'natural';
function getKeySentences(text) {
const tfidf = new analyze.TfIdf();
tfidf.addDocument(text);
return tfidf.listTerms(0).slice(0,3).map(term => term.term);
}
阅读进度动态摘要 根据用户滚动位置动态显示不同部分的摘要。
function useScrollSummary(content) {
const [summary, setSummary] = useState('');
useEffect(() => {
const paragraphs = content.split('\n');
const handleScroll = () => {
const scrollPercent = window.scrollY / document.body.scrollHeight;
setSummary(paragraphs[Math.floor(scrollPercent * paragraphs.length)]);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, [content]);
return summary;
}
样式优化建议
- 为摘要添加淡出效果:使用CSS
mask-image属性创建渐变遮罩 - 响应式断点:在不同屏幕尺寸下调整摘要长度
- 主题适配:根据暗色/亮色模式调整摘要文字对比度
.article-excerpt {
mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
max-height: 200px;
overflow: hidden;
}
@media (max-width: 768px) {
.article-excerpt {
max-height: 150px;
}
}



