使用<img>为markdown gatsbyjs创建自定义组件

Har*_*tal 5 javascript markdown components reactjs gatsby

我正在尝试为我的Markdown创建一个接受图像源的自定义组件。我无法通过自定义组件显示图片,因为找不到图片,因为图片不存在

我还意识到图像路径是由GatsbyJS生成的,我不知道如何在markdown中检索图像的路径。

我确实有一个自定义组件,其中包含一些文本,但我无法对图像执行相同的操作。

这是一个带有标题和几个单词的简单减价。

index.md

---
title: ToDoApp
---

Hi this is my todoapp app. Below is a bunch of screens

<imageholder src='./screen1.png'></imageholder>
![Image from Gyazo](./screen1.png) <!-- it displays... -->
Run Code Online (Sandbox Code Playgroud)

我创建了一个名为imageholder的自定义组件,该组件在显示图像时拥有一些逻辑(不久之后...)

ImageHolder.js

import React from "react"
   export default class ImageHolder extends React.Component {
   render() {
     return (
       <img src={this.props.src} alt="Logo"/>
     )
   }
 }
Run Code Online (Sandbox Code Playgroud)

project-post.js

const renderAst = new rehypeReact({
  createElement: React.createElement,
  components: {
   "imageholder": ImageHolder
  },
}).Compiler 
Run Code Online (Sandbox Code Playgroud)

我收到了

Der*_*yen 5

这真的很棘手,因为(AFAIK)您无法使用来将道具从页面组件传递到自定义组件rehype-react。我认为您需要执行与相似的操作gatsby-remark-images,以定位图像的路径并进行设置。

我编写的该插件模仿gatsby-remark-images,但适用于您的情况下的自定义组件。

这是默认设置,您可以覆盖组件名称并传递其他图像转换选项。

// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-custom-image-component`,
            options: {
              // plugin options
              componentName: 'image-wrapper',
              imagePropName: 'src',
              sharpMethod: 'fluid',
              // fluid's arguments, see gatsby-plugin-sharp docs
              quality: 50,
              maxWidth: 800,
            }
          },
        ],
      },
    },
Run Code Online (Sandbox Code Playgroud)

然后在减价中使用它:

<image-wrapper src='./hero.jpg'></image-wrapper>
Run Code Online (Sandbox Code Playgroud)

并在您的自定义组件中获取图像道具。

//src/components/ImageWrapper.js
import React from 'react'

// the result of sharp's image transformation will be passed directly to this component.
// so if you use `fluid` as `sharpMethod`, you'll get
// src, srcSet, base64, aspectRatio, srcSetType, sizes, density, originalImage. 
// Please refer to `gatsby-plugin-sharp` docs.
const ImageWrapper =  ({ src, srcSet }) => <img src={src} srcSet={srcSet} />

export { ImageWrapper }
Run Code Online (Sandbox Code Playgroud)