我需要在reactjs应用程序中集成sharethis。我需要该脚本只在一个组件中执行。目前这是我实施的方式。
componentWillMount() {
const script = document.createElement("script");
script.src ="//platform-api.sharethis.com/js/sharethis.js#property=242434664&product=sop?r=" +new Date().getTime();
script.async = true;
script.id = "shareThisId";
document.body.appendChild(script);
}
这个问题是因为这个组件是通过反应路由安装的,并且页面重新加载不会发生,所以脚本不会重新执行。
我尝试使用removeChild删除componentWillUnmount生命周期中的脚本标记,但是仍然没有在挂载时重新执行脚本,并且我了解到它是因为这样 - 根据https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild,删除的子节点仍然存在于内存中。
此外,脚本需要在mount上重新执行,以便每次都获得更新的共享计数。
我在sharethis工作,最近我们在https://www.npmjs.com/package/sharethis-reactjs发布了一个reactjs插件。您可以尝试更方便地安装和使用它。
如果您在使用过程中遇到任何问题,请告诉我,我很乐意为您提供帮助。
郝旭,为了它的价值,我厌倦了试图让“官方”分享这个反应包的工作......
您需要在index.html中包含js
<script type='text/javascript' src='//platform-api.sharethis.com/js/sharethis.js#property=YOUR-PROPPERTY-KEY&product=inline-share-buttons' async='async'></script>
所以这就是我写的......你当然希望按照你的方式进行配置
import React, {Component} from 'react'
import {isMobile} from 'react-device-detect';
export class ShareButtons extends Component{
constructor(props){
super(props);
var defaultNetworks = isMobile ? ['facebook', 'twitter', 'pinterest', 'googleplus', 'sharethis', 'sms', 'email']
: ['facebook', 'twitter', 'pinterest', 'googleplus', 'sharethis', 'email'];
this.state = {
config: {
id: this.props.id || 'sharethis-inline-buttons',
networks: this.props.networks || defaultNetworks,
alignment: this.props.alignment || "right",
enabled: this.props.enabled !== 'false' || true,
font_size: this.props.font_size || 11,
padding: this.props.padding || 8,
radius: this.props.radius || 20,
networks: this.props.networks || defaultNetworks,
size: this.props.size || 32,
show_mobile_buttons: this.props.show_mobile_buttons !== 'false' || true,
spacing: this.props.spacing || 2,
url: this.props.url || window.location.href,
title: this.props.title || document.title,
image: this.props.image || "https://18955-presscdn-pagely.netdna-ssl.com/wp-content/uploads/2016/12/ShareThisLogo2x.png", // useful for pinterest sharing buttons
description: this.props.description || document.getElementsByTagName('meta')["description"].content,
username: this.props.username || "ChadSteele" // custom @username for twitter sharing
}
};
}
componentDidMount(){
window.__sharethis__.load('inline-share-buttons', this.state.config);
}
render(){
return <span id={this.state.config.id || 'sharethis-inline-buttons'}></span>
}
}
export default ShareButtons;