如何呈现 oembed 标签 url

mcc*_*osa 6 wysiwyg oembed reactjs strapi

我正在 Strapi 上使用 WYSIWYG 富文本插件。添加媒体 url 返回以下字符串,然后我dangerouslySetInnerHTML在 React 中使用该字符串将其转换为 HTML。

<figure class="media">
   <oembed url="https://www.youtube.com/watch?v=dQw4w9WgXcQ"></oembed>
</figure>
Run Code Online (Sandbox Code Playgroud)

但这不会在浏览器中呈现 YouTube 视频。

我不确定如何让它渲染。查看 oEmbed,大多数情况下它似乎会转换为 iframe,但不确定当它从 HTTP 请求响应作为字符串返回时如何执行此操作。

小智 2

您可以使用oembed pluginWYSIWYG 插件提供的功能将<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 }} />;
};
Run Code Online (Sandbox Code Playgroud)