
## 小程序分享api痛點:
我們開發(fā)小程序分享時都知道,小程序分享的出口及入口過多,每個頁面中都要使用onShareAppMessage,這樣并不方便我們進(jìn)行管理。
什么是Decorator:
Decorator就是一個用于裝飾類和類的方法,我們完全可以寫一個share的裝飾器去裝飾不同的頁面(類), 后面只需要維護(hù)share的裝飾器即可
## 直接上代碼:
withShare.js
```
import Taro from '@tarojs/taro';
import { getBehaviorAnalysis } from '@/actions/global';
function withShare(opts) {
? return function shareComponent(Component) {? ? ?
? ? class WithShare extends Component {
? ? ? async componentWillMount() {
? ? ? ? Taro.showShareMenu({
? ? ? ? ? withShareTicket: true
? ? ? ? });
? ? ? ? if (super.componentWillMount) {
? ? ? ? ? super.componentWillMount();
? ? ? ? }
? ? ? }
? ? ? createShareOpts (res) {
? ? ? ? // 寫相應(yīng)的路徑進(jìn)行處理,給出type值做出判斷,最好是 key-value值
? ? ? }
? ? ? onShareAppMessage(res) {
? ? ? ? // 判斷分享按鈕來自哪里
? ? ? ? if (res.from === 'menu') {
? ? ? ? }
? ? ? ? return this.createShareOpts(res)
? ? ? }
? ? ? render() {
? ? ? ? return super.render();
? ? ? }
? ? }
? ? return WithShare;
? };
}
export default withShare;
使用方法:
import Taro, { Component } from '@tarojs/taro';
import { View } from '@tarojs/components';
import withShare from './withShare';
@withShare({
? ? title: '可設(shè)置分享標(biāo)題',
? ? imageUrl: '可設(shè)置分享圖片路徑',
? ? path: '可設(shè)置分享路徑'
})
class Index extends Component {
? render() {
? ? return (<View></View>)
? }
}
```
## 使用方法:
```
import Taro, { Component } from '@tarojs/taro';
import { View } from '@tarojs/components';
import withShare from './withShare';
@withShare({
? ? title: '可設(shè)置分享標(biāo)題',
? ? imageUrl: '可設(shè)置分享圖片路徑',
? ? path: '可設(shè)置分享路徑'
})
class Index extends Component {
? render() {
? ? return (<View></View>)
? }
}
```
## 近期:
[教你寫一個快速提交git代碼的shell腳本](https://mp.weixin.qq.com/s/ce262xICrOrZe9fZezUITQ)
大家可以關(guān)注下‘前端開發(fā)社區(qū)’公眾號,里面有500G的學(xué)習(xí)資源供大家學(xué)習(xí)。大家也可以進(jìn)前端技術(shù)交流群或者關(guān)注我的博客,謝謝大家!


