Your query should look like:
query {
allContentfulBlogPost {
edges {
node {
bodyRichText {
raw
references {
... on ContentfulAsset {
contentful_id
fixed(width: 1600) {
width
height
src
srcSet
}
}
... on ContentfulBlogPost {
contentful_id
title
slug
}
}
}
}
}
}
}
Note the:
fixed(width: 1600) {
width
height
src
srcSet
}
Note: additionally you can use one of the GraphQL fragments exposed like ...GatsbyContentfulFixed
. More details: https://www.gatsbyjs.com/plugins/gatsby-image/
If you are using gatsby-image
you need a bunch of additional fields like the ones in the snippet above. If you are using a standard <img>
tag, you just need the source (src
) of the image.
At this point, you'll need to use something like:
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 => {
console.log("embedded asset",node)
return (
<>
<h2>Embedded Asset</h2>
<pre>
<code>{JSON.stringify(node, null, 2)}</code>
</pre>
</>
)
},
[BLOCKS.EMBEDDED_ENTRY]: node => {
console.log("embedded entry",node)
return (
<>
<h2>Embedded Entry</h2>
{/* Using gatsby-image */}
<Img fixed={node.target.sys.id.references.fixed} />
{/* Using img */}
<img src={node.target.sys.id.references.fixed.src} />
</>
)
},
},
}
renderRichText(node.bodyRichText, options)
I'm assuming that the nesting structure (node.target.sys.id.references.fixed
) is correct, if not, try debugging, starting at node
using the console.logs
as support.
Useful resources:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…