Moh*_*eem 1 bots reactjs next.js sanity
如何使用 sanity 作为后端和 next js 作为前端以可移植文本显示来自(块内容)富文本的图像。
我的便携式文本看起来像这样
<PortableText
value={blog.body}
/>
Run Code Online (Sandbox Code Playgroud)
没有变量或常量与之关联。
显示所有文本和其他字段(需要图像)。
您可以传递组件对象来呈现自定义内容类型,例如图像。
首先,为您的 PortableText 自定义组件创建一个对象,并返回该image类型的图像组件。
const myPortableTextComponents = {
types: {
image: ({ value }) => {
return (
<SanityImage {...value} />
);
},
},
};
Run Code Online (Sandbox Code Playgroud)
第二:创建您的 ImageComponent。我在这里使用next-sanity-image插件将图像与 NextJS Image 组件一起使用。
import {useNextSanityImage} from 'next-sanity-image'
import Image from 'next/image';
const sanityConfig = sanityClient({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
useCdn: true
});
const SanityImage = ({ asset }) => {
const imageProps = useNextSanityImage(sanityConfig, asset);
if (!imageProps) return null;
return (<Image
{...imageProps}
layout='responsive'
sizes='(max-width: 800px) 100vw, 800px'
/>);
}
Run Code Online (Sandbox Code Playgroud)
最后,通过 prop 将自定义组件对象传递给您的 PortableText 组件components。
<PortableText
value={body}
components={myPortableTextComponents}
/>
Run Code Online (Sandbox Code Playgroud)
您可以在此处了解有关在 React 中渲染 PortableText 的更多信息,以及有关 next-sanity-image 插件的更多信息。
| 归档时间: |
|
| 查看次数: |
3830 次 |
| 最近记录: |