分享功能
小程序开发的项目本身通常就是作为一个引流的工具,所以分享是很重要的一个功能;
在小程序中,最常见的分享主要有三种方式:
- 小程序右上角自带的分享功能,分享给好友;
- 小程序右上角自带的分享功能,分享到朋友圈;
- 通过Button组件的open-type属性,手动触发分享;
1. 小程序右上角_分享给微信好友
具体实现步骤:
-
- 首先是在页面配置中,配置enableShareAppMessage属性为true;这个时候打开小程序右上角,你可以发现分享给好友的按钮不是置灰的了;
分享到朋友圈的属性还未配置,这时候就是置灰的;
- 2.其实完成上一步,该页面就已经可以正常分享了;但是往往我们需要自定义分享出去的样子,比如说,分享出去的标题,封面等,具体可参照官方文档;小程序的分享onShareAppMessage
官方文档给我们提供了页面的处理函数onShareAppMessage来监听用户的分享行为;
我这里用的是taro框架的,其实本质都一样
useShareAppMessage((res) => {
console.log(res);
return {
title: '小程序分享的标题',
path: '/pages/index/index', // 指定打开小程序的页面
imageUrl: 'https://c-ssl.duitang.com/uploads/blog/202210/07/20221007105703_c0925.jpeg', // 分享的封面
}
})
分享出去的模拟效果,(具体以真机为主)
- 3. 自定义的时候,promise我理解的是如果分享出去的内容需要通过请求获得时,提供的方式,如果三秒内没有返回就会使用我们配置的默认值;
useShareAppMessage((res) => {
console.log(res);
const promise = new Promise(resolve => {
setTimeout(() => {
resolve({
title: '自定义resolve转发标题'
})
}, 2000)
})
return {
title: '小程序分享的标题',
path: '/pages/index/index', // 指定打开小程序的页面
imageUrl: 'https://c-ssl.duitang.com/uploads/blog/202210/07/20221007105703_c0925.jpeg', // 分享的封面
promise
}
})
这个时候它的页面效果就变成了promise的内容:
2. 小程序右上角_分享到朋友圈
具体实现步骤跟分享到好友是类似的:
-
- 在页面配置enableShareTimeline,注意一下,只配置这个属性时,分享到朋友圈的按钮是置灰的,需要定义对应的函数:onShareTimeline();
-
- 小程序分享的事件函数: onShareTimeline()
代码示例(我这里用的是taro):
useShareTimeline(() => {
return {
title: '自定义分享到朋友圈的标题',
imageUrl: 'https://c-ssl.duitang.com/uploads/blog/202210/07/20221007104845_38a69.jpeg'
}
})
具体效果以真机为主:
- 需要注意的点:
-
- 分享到朋友圈的配置属性比分享到好友的要少,具体要看官方文档;
-
- 官方文档中描述,分享到朋友圈的前提条件是必须要配置分享给好友,而且还有很多别的限制,一定要注意啦!
-
官方文档截图:
3. Button_openType
按钮的这种分享也是微信官方的开放能力之一;
具体使用步骤:
-
- 在Button组件中配置openType为share;
-
- 如果需要自定义同样使用useShareAppMessage来监听用户的分享行为; 具体代码:
import React from 'react';
import { Button, View } from '@tarojs/components';
import { useShareAppMessage, useShareTimeline } from '@tarojs/taro';
import './index.scss';
const TestShare = () => {
useShareAppMessage((res) => {
console.log(res);
const promise = new Promise(resolve => {
setTimeout(() => {
resolve({
title: '自定义resolve转发标题'
})
}, 2000)
})
return {
title: '小程序分享的标题',
path: '/pages/index/index', // 指定打开小程序的页面
imageUrl: 'https://c-ssl.duitang.com/uploads/blog/202210/07/20221007105703_c0925.jpeg', // 分享的封面
promise
}
})
useShareTimeline(() => {
return {
title: '自定义分享到朋友圈的标题',
imageUrl: 'https://c-ssl.duitang.com/uploads/blog/202210/07/20221007104845_38a69.jpeg'
}
})
return (
<View className='share-wrapper'>
小程序的分享功能
<Button type='primary' openType='share'>分享按钮</Button>
</View>
);
};
export default TestShare;
参考文章:微信小程序之分享功能