如何呈现oembed标签url



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

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

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

我不确定如何去获得这个渲染。看看oEmbed,它似乎在大多数情况下,它转换为iframe,但不确定如何做到这一点,当它从HTTP请求响应返回字符串。

您可以使用所见即所得插件提供的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 }} />;
};

最新更新