0

我正在使用查看器(并排)制作降价编辑器。

我面临一个问题,在 Markdown 中键入图像的语法会导致

Unhandled Runtime Error
Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {"width":600,"height":300}

输入![]()用于插入降价图像的样板代码会导致错误发生。有谁知道处理这个问题的方法?

这是我的代码

import { FC } from "react";
import Image from "next/image";
import ReactMarkdown, { } from "react-markdown";

interface Props {
  props: string
}

const Markdown:FC<Props> = ({props}) => {
  const MarkdownComponents: Object = {
    p: (paragraph: any) => {
      const { node } = paragraph;

      if (node.children[0].tagName === "img") {
        try {
          const image = node.children[0];
          const alt = image.properties.alt?.replace(/ *\{[^)]*\} */g, "");
          const isPriority = image.properties.alt?.toLowerCase().includes('{priority}');
          const metaWidth = image.properties.alt.match(/s{([^}]+)x/);
          const metaHeight = image.properties.alt.match(/x([^}]+)}/);
          const width = 600// metaWidth ? metaWidth[1] : "600";
          const height = 300//metaHeight ? metaHeight[1] : "300";
          

          return (
            <Image
              src={image.properties.src}
              width={width}
              height={height}
              className="postImg"
              alt={alt}
              priority={isPriority}
              layout="responsive"
            />
          )
        } catch (error) {
          console.log(error)
        }
      }
      return <p>{paragraph.children}</p>
    }
  }

  return (
    <ReactMarkdown 
      className="prose"
      components={MarkdownComponents}
    >
      {props}  
    </ReactMarkdown>
  )

}

export default Markdown;
4

1 回答 1

0

没关系,只是添加了条件返回<Image />来检查是否image.properties.src存在:

if (image.properties.src) return (
  <Image ...props />
)

我不知道这是否是最佳或最佳解决方案,但它对我有用

于 2022-01-18T09:00:38.090 回答