如何在 Gatsby 中使用带有富文本的内联图像?

How can I use inline images with rich text in Gatsby?

我正在尝试重新创建一个内嵌小图片的文本。

像这样:

我在 Contentful 中设置了一个带有富文本的内容模型,但我可以插入图像的唯一方法是作为一个块。

比我在Gatsby查询的数据:

const data = useStaticQuery(graphql`
  query { 
    contentfulHomepage {
      breaks {
        id
        shout {
          json
        }
      }
    }
  }
`)

下面是我用 gatsby 获取富文本的方式:

const options = {
  renderNode: {
    'embedded-asset-block': node => {
      const alt = node.data.target.fields.title['en-US']
      const url = node.data.target.fields.file['en-US'].url
      return <img src={url} alt={alt} />
    },
  },
}

const breaks = data.contentfulHomepage.breaks.map(element => (
  <Break
    key={element.id}
    shout={documentToReactComponents(element.shout.json, options)}
  />
))

我得到的数据是正确的,但是节点的呈现方式是在几个段落和中间的图像之间。 像这样:

<p>If you are </p>
<img alt...>
<p>already intrigued</p>
<img alt...>
...

有没有办法在段落块中将图像作为内联跨度(或其他)获取? 就像是: <p>Some text<span><img></img></span> and other <span><img></img></span> text </p>

谢谢

听起来你已经弄清楚了 React 和 Gatsby 部分,除非你准备修改标记,否则你可以用 CSS 解决这个问题。

这样的东西行得通吗? https://codesandbox.io/s/throbbing-leftpad-rlsh3?file=/src/styles.css

.Shout p {
  display: inline;
}

.Shout img {
  display: inline;

  /* Setting the max height of the image
     in ems, so it will scale with the font
     size set in the `.Shout` CSS class.
       You’ll probably want to adjust this
     to roughtly match the x-height or cap height
     of the font you are using. */
  max-height: 0.85em;

  /* If there aren’t spaces in the phrases,
     you might add margins around the images.
     Asjust as you see fit. */
  margin-left: 0.25em;
  margin-right: 0.25em;
}

…其中 Shout 是包含节点的 React 组件上的 CSS class(或如 the CodeSandbox example)。

const Shout = props => {
  return (
    <div className="Shout">
      <p>If you are</p>
      <img src="https://source.unsplash.com/random/400x300" />
      <p>already intrigued</p>
      <img src="https://source.unsplash.com/random/500x200" />
      <p>and also think about</p>
      <img src="https://source.unsplash.com/random/250x250" />
      <p>while remembering to</p>
      <img src="https://source.unsplash.com/random/400x300" />
    </div>
  );
};

如果您对图像与文本的环绕方式有更严格的要求,则可能需要从此处开始构建它,但希望这有助于入门。