【问题标题】:How to replace HTML images with GatsbyJS responsive images?如何用 GatsbyJS 响应式图像替换 HTML 图像?
【发布时间】:2019-07-26 03:47:25
【问题描述】:

我正在使用 Directus 7 source 从 GatsbyJS 中的 Directus CMS 查询数据,如下所示:

query {
  allDirectusBlog {
    edges {
      node {
        name
        body
      }
    }
  }
}

我的问题是body 实际上是带有指向我的 Directus 服务器的图像标签的原始 HTML。这通常很好,但是这些图像非常大,即使通过 WiFi 也需要相当长的时间来加载。有没有办法在构建时用 Gatsby 响应图像替换这些 <img> 标签?

【问题讨论】:

    标签: reactjs image gatsby directus


    【解决方案1】:

    我创建了一个函数,使用html-react-parser 和 WordPress 的帖子内容来替换 Gatsby 的所有 img 和 static 文件夹中提供的图像。

    如果您想要一种方法来做到这一点,这是我的代码的一部分,您可以根据您的项目进行调整(这是 WIP 功能,但效果很好)

    export const ParsePostContentHTML = dataContent => {
    
        let indexKeyImg = 234;
    
        const ParsedHTML = Parse(dataContent, {
            replace: function(domNode) {
                if(domNode.name === 'img') {
    
                    const fluidImg = data.allWordpressWpMedia.edges.filter(media => {
                        return media.node.source_url === domNode.attribs.src
                    })
    
                    if(fluidImg.length > 0) {
                        let srcMedia = (fluidImg[0].node.localFile.childImageSharp)
                            ? fluidImg[0].node.localFile.childImageSharp.fluid
                            : fluidImg[0].node.localFile.publicURL
    
                        indexKeyImg++
    
                        if(fluidImg[0].node.localFile.childImageSharp) {
                            return (
                                <Img
                                    key={indexKeyImg}
                                    fluid={srcMedia}
                                    className={`${domNode.attribs.class} gatsby-rendered-img`}
                                    alt={fluidImg[0].node.alt_text}
                                />
                            )
                        } else {
                            return (
                                <img
                                    key={indexKeyImg}
                                    src={srcMedia}
                                    className={`${domNode.attribs.class} gatsby-rendered-img`}
                                    alt={fluidImg[0].node.alt_text}
                                />
                            )
                        }
                    }
                }
            }
        })
    
        return ParsedHTML
    }
    

    您只需在您的组件/模板中导入此函数并将其与ParsePostContentHTML(YourPostContent) 一起使用

    希望对你有所帮助!

    【讨论】:

    • 感谢您的回复!我可能会考虑为这类事情编写一个 Gatsby 转换器,你介意我使用其中的一些代码吗?
    • (对不起,因为我的名声,我不能投票。我还没有做太多)
    • @somebody0 没问题,你想用都可以!
    猜你喜欢
    • 2012-08-24
    • 2020-03-25
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 2015-12-27
    • 2019-02-28
    相关资源
    最近更新 更多