在开发小程序的时候遇到自定义分享按钮分享卡片到好友的需求,由于小程序的分享只有在页面js中定义了onShareAppMessage(Object)方法才会出现右上角的分享按钮,所以需要在页面中自定义分享方法。具体见下:
object参数
onShareAppMessage(Object)事件需要返回一个Object对象对象里面包含要分享的标题,转发的路径,以及自定义图片的路径。完成了这一系列操作就可以愉快的去分享微信小程序的页面了。
// 在页面中使用
import Taro, { Component } from "@tarojs/taro";
import { View } from "@tarojs/components";
class index extends Component {
onShareAppMessage() {
return {
title: "自定义标题",
path: '/page/user?id=123', // 自定义的分享路径,点击分享的卡片之后会跳转这里定义的路由
imageUrl: '' // 图片路径
};
}
render(){
return(
<View>微信分享</View>
)
}
}
export default index;
自定义分享按钮事件的实现。有时候,在大多数的业务场景下我们需要在页面中点击某个按钮触发分享的事件,此时需要监听用户点击页面内转发按钮(Button 组件 openType=‘share’)就会自动触发onShareAppMessage方法。如果需要在button中携带信息,需要自定义button属性,通过res.target.dataset获取。
// 在页面中使用
import Taro, { Component } from "@tarojs/taro";
import { View } from "@tarojs/components";
class index extends Component {
onShareAppMessage(res) {
if (res.from === "button") {
const {share = {}} = res.target.dataset
return {
title:`自定义分享按钮${share.title}`,
path: `/pages/bill/index`,
imageUrl: ''
};
} else {
return {
title: "右上角分享事件",
path: `/pages/bill/index`,
imageUrl: ''
};
}
}
render(){
return(
<View>
<Button open-type="share" data-share={data} >
点击分享
</Button>
</View>
)
}
}
export default index;
需要注意的是,onShareAppMessage不支持异步调用,如果有需求是先请求接口的数据再分享会因为拿不到数据导致分享信息不正确的错误。