【发布时间】:2021-10-31 00:48:10
【问题描述】:
【问题讨论】:
标签: graphql gatsby gatsby-image directus ssg
【问题讨论】:
标签: graphql gatsby gatsby-image directus ssg
如果您想在原始 HTML (content) 中显示您的图像,您将需要使用 dangerouslySetInnerHTML 或使用降价解析器。 imageFile 节点可以单独隔离打印。
您只需要使用page query 来获取您的数据,例如:
import * as React from 'react'
import { graphql } from 'gatsby'
import Markdown from 'markdown-to-jsx';
const HomePage = ({data}) => {
console.log("Your data is", data);
return (
<div>
Your image is: <img src={data.article.image.imageFile.publicURL} alt="" />
Your content is:
<Markdown>{data.article.content}</Markdown>
</div>
)
}
export const query = graphql`
query directus{
article {
id
title
description
content
image {
imageFile {
publicURL
}
}
}
}
`
export default HomePage
注意:我的查询基于您的 GraphQL 架构,并对其进行调整以适应您的。
您查询的数据存储在props.data 中(在这种情况下被解构为data),那么您只需要在每种情况下获取所需的节点即可。对于您的图像,您需要继续嵌套对象,直到到达publicURL。
关于其余内容,我使用了markdown-to-jsx库,使用起来非常简单,但你可以省略它,直接使用dangerouslySetInnerHTML或其他库。
【讨论】:
markdown-to-jsx) 或 React(如果您使用 dangerouslySetInnerHTML)。这是因为您获取了所有原始 HTML(<p>,@ 987654335@等)
/static 文件夹中的所有内容克隆到公共文件夹中,因此该图像将在您的站点上可用(我的意思是图像的来源)。如果图像存在,我认为它会单独工作。
src 参考directus 主机上的图像。需要将图像加载到 gatsby static 路径
我解决的问题如下:
CustomImage 组件,我在其中检查了 id。overrides 选项替换Markdown 组件中的img 标记。所以,我的代码看起来是这样的:
布局道具:
interface ArticleImage {
directus_files_id: {
id: string;
imageFile: IGatsbyImageData;
}
}
interface BlogLayoutProps {
title: string;
annotation: string;
imageData: IGatsbyImageData;
allImages: Array<ArticleImage>;
content: string;
}
自定义图片组件:
const CustomImage = (props) => {
const { alt, width, height, src } = props;
const image = allImages.find(i => src.indexOf(i.directus_files_id.id) !== -1);
if (image) {
const imgData = getImage(image.directus_files_id.imageFile);
imgData.width = +width;
imgData.height = +height;
return <GatsbyImage image={imgData} alt={alt}/>;
}
return <img src={src} width={width} height={height} alt={alt} />
};
在布局组件中:
<StyledContent>
<Markdown
options={{
overrides: {
img: {
component: CustomImage,
}
}
}}
>
{content}
</Markdown>
</StyledContent>
页面查询:
query MyQuery {
directus {
article_by_id(id: "26434049-7bb4-46d3-8ad1-c04973b9cf71") {
id
category {
id
title
}
title
description
content
image {
id
width
height
imageFile {
childImageSharp {
gatsbyImageData
}
}
}
imagelist {
directus_files_id {
id
imageFile {
childImageSharp {
gatsbyImageData
}
}
}
}
}
}
}
我希望有人能帮助我解决问题或推动他产生新的想法!
【讨论】: