【问题标题】:How to embed Twitter widget to Reactjs?如何将 Twitter 小部件嵌入到 Reactjs?
【发布时间】:2021-04-22 04:39:52
【问题描述】:

访问 twitter 小部件站点 (https://publish.twitter.com/) 我可以获取要添加到我的站点的小部件。我正在使用示例代码来尝试理解它的工作原理:

<a class="twitter-grid" href="https://twitter.com/TwitterDev/timelines/539487832448843776">National Park Tweets</a> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

如果我只是将它添加到 HTML 页面,那么代码将完全按照应有的方式工作。它显示了带有相应推文的网格。

然而,当我把它添加到 ReactJS 时,我看到的只是后备代码,它只提供了一个指向 twitter 用户名的链接。

我尝试使用以下方法无济于事:

  <div dangerouslySetInnerHTML={{__html: "<a className='twitter-grid' href='https://twitter.com/TwitterDev/timelines/539487832448843776'>National Park Tweets</a> <script async src='https://platform.twitter.com/widgets.js' charset='utf-8'></script>"}}>
  </div>

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    查看这个 npm 包:react-twitter-widgets。这似乎可以满足您开箱即用的需求。

    import { Tweet } from 'react-twitter-widgets'
    
    ReactDOM.render(<Tweet tweetId='511181794914627584'/>, document.getElementById('root'))
    

    【讨论】:

    • 这一切都很好。但我没有在节点环境中运行它。
    • 你不是也在使用 npm 来管理你的 React 包吗?它不必在服务器中运行。
    • 这是一个静态 html 文件,我打算放在 codepen 上。
    • 是的,你会在使用这种方法时遇到一些麻烦(在寻找在线帮助/教程/等方面)...最好的办法是保留一个 src 文件夹并使用 CommonJS/ES6组件在本地构建您的应用程序,然后使用 webpack 将其捆绑到一个漂亮的 js 文件中以上传到 codepen。你的应用程序有多复杂?在某些时候,React 甚至可能无法满足您的需求。
    • 如果OP只需要embedding,react-tweet-embed就足够了。
    【解决方案2】:

    我不知道其他人是否仍然有这个问题,但在我的情况下,我从 API 获取文章正文内容,只是将该 html 插入到 div 中,但无法让推文正常工作。

    只是想出了一个解决方案,所以我的 index.html 中有小部件 js。

    然后在组件更新时,我检查我的文章内容是否已加载,然后只需调用 twttr.widgets.load()

    这是我的 componentDidUpdate 函数:

    componentDidUpdate(props) {
          if(this.props.article.status === 'FULFILLED' && this.props.article.status !== props.article.status) {
            twttr.widgets.load(
              document.getElementById('article')
            )
          }
        }
    

    希望其他人觉得这很有用!

    【讨论】:

    • 嘿 :) 你是如何/在哪里实现 twttr 函数的?
    • 那是很久以前的事了,但是 IIRC 我使用的是 twitter JS 库。我无法访问代码,因为从那以后我已经换了几次工作。我敢肯定,现在有很多 twitter 库可供您使用。
    猜你喜欢
    • 2015-07-15
    • 2012-08-31
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2017-01-05
    • 2017-12-25
    相关资源
    最近更新 更多