内容丰富+ Gatsby Rich文字和内嵌图片

时间:2020-05-17 12:19:45

标签: javascript reactjs jsx gatsby contentful

我正在尝试重新创建内部带有小型嵌入式图像的文本。

类似这样的事情: enter image description here

我已经在Contentful中使用RTF设置了内容模型,但是插入图像的唯一方法是作为一个块。

enter image description here

比起盖茨比,我要查询数据:

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>

谢谢

1 个答案:

答案 0 :(得分:1)

听起来您已经弄清楚了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类(或与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>
  );
};

Screenshot showing phrases and images styled using example code

如果您对图像如何用文字换行有更严格的要求,则可能需要在此基础上进行构建,但是希望这有助于上手。