
## 小程序分享api痛点:
我们开发小程序分享时都知道,小程序分享的出口及入口过多,每个页面中都要使用onShareAppMessage,这样并不方便我们进行管理。
什么是Decorator:
Decorator就是一个用于装饰类和类的方法,我们完全可以写一个share的装饰器去装饰不同的页面(类), 后面只需要维护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) {
// 写相应的路径进行处理,给出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: '可设置分享标题',
imageUrl: '可设置分享图片路径',
path: '可设置分享路径'
})
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: '可设置分享标题',
imageUrl: '可设置分享图片路径',
path: '可设置分享路径'
})
class Index extends Component {
render() {
return (<View></View>)
}
}
```
## 近期:
[教你写一个快速提交git代码的shell脚本](https://mp.weixin.qq.com/s/ce262xICrOrZe9fZezUITQ)
大家可以关注下‘前端开发社区’公众号,里面有500G的学习资源供大家学习。大家也可以进前端技术交流群或者关注我的博客,谢谢大家!



网友评论