在开发小程序的时候遇到自定义分享按钮分享卡片到好友的需求,由于小程序的分享只有在页面 js 中定义了 onShareAppMessage(Object)方法才会出现右上角的分享按钮,所以需要在页面中自定义分享方法。具体见下:
object 参数

onShareAppMessage(Object)事件需要返回一个 Object 对象对象里面包含要分享的标题,转发的路径,以及自定义图片的路径。完成了这一系列操作就可以愉快的去分享微信小程序的页面了。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 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 获取。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| 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 不支持异步调用,如果有需求是先请求接口的数据再分享会因为拿不到数据导致分享信息不正确的错误。