【问题标题】:How to display dynamic text and images with sanity?如何理智地显示动态文本和图像?
【发布时间】:2022-12-29 21:57:50
【问题描述】:
 index.js                                         export const        
 getServerSideProps = async () => {
 const query = '*[_type == "product"]';
 const products = await client.fetch(query);

 const bannerQuery = '*[_type == "banner"]';
 const bannerData = await client.fetch(bannerQuery);

 return {
 props: {products, bannerData}
 }import { urlFor } from '../lib/client';

 HeroBanner.JSX
 const HeroBanner  = ({heroBanner}) => {
  return (
 <div className='hero-banner-container'>
  <div>
    <p className='beats-solo'> {heroBanner.smallText} </p>
    <h3> {heroBanner.midText} </h3>
    <h1> {heroBanner.largeText1} </h1>
    {console.log(heroBanner.largeText1)}
    <img src={urlFor(heroBanner.image)} alt='Trending'      
className='hero-banner-image' />

Client.js
import sanityClient from '@sanity/client';
import imageUrlBuilder from '@sanity/image-url';

export const client = sanityClient({
projectId:'*********',
dataset:'production',
apiVersion:'2022-12-04',
useCdn:true,
token:process.env.NEXT_PUBLIC_SANITY_TOKEN
});

const builder = imageUrlBuilder(client);

export const urlFor = (source) => builder.image(source);

这是我试过的代码。如果普通文本位于 p、h1 和 h3 元素中,则它工作正常。但是,我现在的代码是
{heroBanner.smallText} 这就是我的问题开始的地方。当我使用这些值时,文本不显示。我确实通过 localhost 将 sanity.io 上的值更改为我想要的值,但没有任何显示。 P.S:当我在控制台记录 bannerData 时,我得到了我现在要显示的值。

【问题讨论】:

    标签: reactjs web text e-commerce sanity


    【解决方案1】:

    sanity body 文本没有显示,你需要使用 block-content 来转换它

    npm 安装@sanity/block-content-to-react --save 从“@sanity/block-content-to-react”导入 SanityBlockContent;

    然后将要显示的文本包装在块内容中。 例如,post.body 是我想要显示的内容,它会像这样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-31
      • 2019-04-11
      • 1970-01-01
      相关资源
      最近更新 更多