如何在我的反应应用程序中嵌入脸书发送按钮

How do I embed a facebook send button in my react app?

本文关键字:按钮 我的 应用程序      更新时间:2023-09-26

我有一个客户端渲染的反应应用程序。我想在我的页面上显示一个脸书发送按钮。

开发人员页面上给出的说明没有告诉我如何操作

https://developers.facebook.com/docs/plugins/send-button#configurator

另外,我没有找到Facebook为他们的SDK发布的npm兼容包。那么如何在反应应用程序中包含SDK呢?

编辑:我尝试在反应中使用一些异步加载器。

import React, { Component } from 'react';
import scriptLoader from 'react-async-script-loader';
@scriptLoader(
  'https://connect.facebook.net/es_ES/sdk.js#xfbml=1&version=v2.5',
)
class FacebookSendButton extends Component {
  componentDidMount() {
    const { isScriptLoaded, isScriptLoadSucceed } = this.props;
    if (isScriptLoaded && isScriptLoadSucceed) {
      console.log('script load success from didMount');
    }
  }
  componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
    if (isScriptLoaded && !this.props.isScriptLoaded) { // load finished
      if (isScriptLoadSucceed) {
        console.log('script load success from receiveProps');
      }
    }
  }
  render() {
    return (
      <div>
       BEFORE FB ROOT.
      <div className="fb-send"
        dataHref="http://www.your-domain.com/your-page.html"
        dataLt ayout="button_count"
      />
      <div id="fb-root"></div>
    </div>
    );
  }
}
export default FacebookSendButton;

这不会呈现脸书发送按钮。

一旦 FB SDK 加载,它会解析页面的整个标记,以查找具有特殊fb-*类的元素。由于 FB 脚本是在初始化模块时加载的,因此 SDK 很可能在您最终挂载组件之前加载。要让它重新处理 DOM,您需要在componentDidMount中添加类似以下内容的内容:

if (window.FB) {
  // Read the entire document for `fb-*` classnames
  FB.XFBML.parse();
}

当然,您可能不希望每次安装发送按钮时都分析整个文档。您可以通过创建对要搜索的 DOM 节点的ref,然后将其传递给 parse() 方法来缩小搜索范围。

componentDidMount() {
  const { isScriptLoaded, isScriptLoadSucceed } = this.props;
  if (isScriptLoaded && isScriptLoadSucceed && window.FB) {
    window.FB.XFBML.parse(this._scope);
  }
}
componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
  if (isScriptLoaded && !this.props.isScriptLoaded) { // load finished
    if (isScriptLoadSucceed && window.FB) {
      window.FB.XFBML.parse(this._scope);
    }
  }
}
render() {
  return (
    <div ref={(s) => this._scope = s}>
      <div id="fb-root"></div>
      <div
        className="fb-send"
        data-href="http://www.your-domain.com/your-page.html"
        data-layout="button_count"
      />
    </div>
  );
}

你会注意到我在这里使用了函数引用的新方法。命名的引用(例如ref="somestr")被React团队弃用和阻止。

我有一个黑客版本,从以下要点开始工作:https://gist.github.com/andrewimm/9fdd0007c3476446986a9f600ba4183f