首页 > 解决方案 > 在使用 React 等前端技术时在网页中显示嵌入的社交数据

问题描述

如何在 reactjs 中显示来自 twitter 的嵌入社交数据,其中已经有脚本标签来设置样式和呈现 twitter 并在数据库表中硬编码一些内容?在单体站点中,它工作正常。在前端基于它不起作用。

例如以文本形式存储在 db 表中的内容:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">I just published “Making Sense of React Hooks” <a href=""></a></p>&mdash; Dan Abramov (@dan_abramov) <a href="https://twitter.com/dan_abramov/status/1057319198626594816?ref_src=twsrc%5Etfw">October 30, 2018</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

这个脚本 twitter 不会加载默认的小部件布局,同时使用它周围的一些段落作为硬编码内容做出反应。

标签: javascriptreactjs

解决方案


问题出在脚本标签中。您可以直接将其添加到 index.html 或componentDidMount像这样使用

componentDidMount () {
     const script = document.createElement("script");

     script.src = "https://platform.twitter.com/widgets.js";
     script.async = true;

     document.body.appendChild(script);
}

检查这个Jsfiddle或者你可能想检查这个npm 包


推荐阅读