gpt4 book ai didi

graphql - Gatsby 内容丰富的嵌入图像

转载 作者:行者123 更新时间:2023-12-03 18:56:50 25 4
gpt4 key购买 nike

正如我所见,在仅原始查询 contentfulBlogPost 时,不再有 json 选项。我能够进行一些更改以从正文中获取所有内容,但该帖子中的图片除外。
如果我在 GraphQL Playground 中进行测试,我可以获得图像 id 和 url,仅此而已。

query {
allContentfulAsset {
edges {
node {
id
file {
url
}
}
}
}
}
我试图找到一个如何获取嵌入图像的示例,但没有运气....
import React from 'react'
import { graphql } from 'gatsby'
import { documentToReactComponents } from '@contentful/rich-text-react-renderer'

import Layout from '../components/layout'


export const query = graphql`
query($slug: String!) {
contentfulBlogPost(slug: {eq: $slug}) {
title
publishedDate(formatString: "MMMM Do, YYYY")
body {
raw
}
}
allContentfulAsset {
edges {
node {
id
file {
url
}
}
}
}
}
`

const Blog = (props) => {
const options = {
renderNode: {
"embedded-asset-block": (node) => {
const alt = node.data.title
const url = node.file.url
return <img alt={alt} src={url}/>
}
}
}
return (
<Layout>
<h1>{props.data.contentfulBlogPost.title}</h1>
<p>{props.data.contentfulBlogPost.publishedDate}</p>
{documentToReactComponents(JSON.parse(props.data.contentfulBlogPost.body.raw, options))}
</Layout>
)
}

export default Blog
插件:
...
'gatsby-plugin-sharp',
{
resolve: 'gatsby-transformer-remark',
options: {
plugins: [
'gatsby-remark-relative-images',
{
resolve: 'gatsby-remark-images-contentful',
options: {
maxWidth: 750,
linkImagesToOriginal: false
}
}
]
}

}
],
}

最佳答案

使用类似的东西:

import { BLOCKS, MARKS } from "@contentful/rich-text-types"
import { renderRichText } from "gatsby-source-contentful/rich-text"

const Bold = ({ children }) => <span className="bold">{children}</span>
const Text = ({ children }) => <p className="align-center">{children}</p>

const options = {
renderMark: {
[MARKS.BOLD]: text => <Bold>{text}</Bold>,
},
renderNode: {
[BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
[BLOCKS.EMBEDDED_ASSET]: node => {
return (
<>
<h2>Embedded Asset</h2>
<pre>
<code>{JSON.stringify(node, null, 2)}</code>
</pre>
</>
)
},
},
}

renderRichText(node.bodyRichText, options)
资料来源: https://www.contentful.com/developers/docs/tutorials/general/rich-text-and-gatsby/ return 条目中的 BLOCKS.EMBEDDED_ASSET 语句将包含您的数据,适应您的需求。如果您进入依赖项,您将看到所有公开的方法,因此您还将有一个 BLOCKS.EMBEDDED_ENTRY 条目用于嵌入的条目。像这样应用它:
[BLOCKS.EMBEDDED_ENTRY]: node => {
// your logic to manipulate the entry here
return (
<>
<div>whatever</div>
</>
)
},

关于graphql - Gatsby 内容丰富的嵌入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65829246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com