reactjs 如何呈现oembed标记url

svmlkihl  于 2022-12-22  发布在  React
关注(0)|答案(1)|浏览(121)

我在Strapi上使用了一个所见即所得的富文本插件,添加一个媒体url返回以下字符串,然后我在React中使用dangerouslySetInnerHTML将其转换为HTML。

<figure class="media">
   <oembed url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"></oembed>
</figure>

但这不会在浏览器中渲染YouTube视频。
我不知道如何去得到这个渲染。看看oEmbed,似乎在大多数情况下,它转换为一个iframe,但不知道如何做,当它作为一个字符串从HTTP请求响应返回。

bfrts1fy

bfrts1fy1#

您可以使用所见即所得插件提供的oembed plugin<oembed>元素转换为<iframe>元素。

const MyComponent = ({ htmlString }) => {
  // Use a regular expression to find the oembed element in the HTML string
  const oembedRegex = /<oembed[^>]*>/g;
  const oembedMatch = htmlString.match(oembedRegex);

  // If an oembed element was found, convert it to an iframe element
  if (oembedMatch) {
    const oembedUrl = oembedMatch[0].match(/url="([^"]*)"/)[1];
    const iframeElement = `<iframe src="${oembedUrl}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
    htmlString = htmlString.replace(oembedRegex, iframeElement);
  }

  return <div dangerouslySetInnerHTML={{ __html: htmlString }} />;
};

相关问题