如何在NextJS项目的Sanity中添加引用块?
在NextJS+Sanity项目中实现自定义引用块
1. 在Sanity Studio定义引用块Schema
首先创建自定义的引用块对象类型,方便在Studio里编辑引用内容:
// schemas/objects/pullQuote.js export default { name: 'pullQuote', type: 'object', title: '引用块', fields: [ { name: 'quote', type: 'text', title: '引用内容' }, { name: 'author', type: 'string', title: '作者(可选)' } ], preview: { select: { title: 'quote', subtitle: 'author' } } }
接着把这个类型添加到博客文章的内容字段中,让它能和普通富文本块混用:
// schemas/documents/blogPost.js export default { name: 'blogPost', type: 'document', title: '博客文章', fields: [ // 标题、slug等其他字段... { name: 'body', type: 'array', title: '文章内容', of: [ { type: 'block' }, // 默认富文本块 { type: 'pullQuote' } // 自定义引用块 ] } ] }
2. 在NextJS前端渲染并添加样式
先确保安装了Portable Text的React组件:
npm install @portabletext/react
创建引用块渲染组件:
// components/PullQuote.js export default function PullQuote({ value }) { return ( <blockquote className="pull-quote"> <p>{value.quote}</p> {value.author && <cite>— {value.author}</cite>} </blockquote> ) }
添加自定义样式(可根据你的设计调整颜色、间距):
.pull-quote { margin: 2rem 0; padding: 1.5rem 2rem; border-left: 4px solid #2563eb; background-color: #f8fafc; font-size: 1.125rem; line-height: 1.8; } .pull-quote cite { display: block; margin-top: 1rem; font-size: 0.875rem; color: #64748b; font-style: normal; text-align: right; }
最后在博客页面中配置Portable Text组件,关联自定义类型:
// app/blog/[slug]/page.js import { PortableText } from '@portabletext/react' import PullQuote from '@/components/PullQuote' import { getBlogPostBySlug } from '@/lib/sanity' // 配置自定义组件映射 const portableTextComponents = { types: { pullQuote: PullQuote } } export default async function BlogPost({ params }) { const post = await getBlogPostBySlug(params.slug) return ( <article className="max-w-3xl mx-auto px-4 py-8"> <h1 className="text-3xl font-bold mb-6">{post.title}</h1> <PortableText value={post.body} components={portableTextComponents} /> </article> ) }
内容的提问来源于stack exchange,提问作者Suleyman Eminbeyli
相关产品推荐
相关产品推荐

