微信小程序+Taro 混编,Taro 使用微信原生 behaviors

最近有一个小程序项目,因为一些原因项目架构选择了微信小程序原生+Taro 混编的方式进行开发,在开发的过程中发现 Taro 不支持使用原生的 behaviors 特性,因为混编的原因项目当中已有原生页面在使用 behaviors,所以需要一个方案在不影响其他页面的基础上使 Taro 也能使用这一特性。

behaviors 除了有类似 Mix 的效果,还有生命周期的封装性。所以咱们考虑的方向就是实现这两点就可以了。

最终以挂载一个空的原生组件(它使用了 behaviors)到 Taro 页面做为中转的方式解决了这一棘手的问题。通过中转组件就可以在 Taro 页面调用到 behaviors 的方法,以及使用 behaviors 生命周期的封装。

switchAccountBehaviors.js:

objectivec 复制代码
export default Behavior({
	pageLifetimes: {
        show: function () {
            this.judgeSwitchAccountRefresh();
        }
    },
	methods: {
		const judgeSwitchAccountRefresh = () => {
			// do...
		},
		const doSome = () => {
			// do...
		}
	}
});

wxml 为空的中转组件,路径:@/behaviors/components

objectivec 复制代码
import switchAccountBehaviors from "@/behaviors/switchAccountBehaviors";

Component({
    properties: {},
    data: {},
    behaviors: [switchAccountBehaviors],
    methods: {}
});

Taro 页面的 index.config.js:

objectivec 复制代码
export default ({
  usingComponents: {
    // 定义需要引入的第三方组件
    // 1. key 值指定第三方组件名字,以小写开头
    // 2. value 值指定第三方组件 js 文件的相对路径
    "behaviors-component": "@/behaviors/components",
  }
});

Taro 页面的 index.jsx

objectivec 复制代码
// Taro 页面调用 behaviors 的方法
getCurrentInstance()?.selectComponent("#behaviors-component")?.doSome();

render() {
	...
	return (
		<>
			...
			<behaviors-component id="behaviors-component" /> 
		</>
	)
}
相关推荐
307615 小时前
uni-app在微信小程序国际化分包方案:优雅解决主包体积超限问题
微信小程序
S1998_1997111609•X19 小时前
滄集/㞯鎩.赫量被恶意篡改?|\^*仺\~:sall,sql=㶏齾bci.ji.app_sql=-heart{TCP.box}‘雧……㞋
网络·数据库·网络协议·百度·微信
wechatbot8881 天前
企业微信管理系统:企业私域流量自动化运营api接口开发实战指南
运维·微信·自动化·企业微信·ipad
打瞌睡的朱尤1 天前
微信小程序50~75
微信小程序·小程序
wechatbot8881 天前
极客互动企业微信聚合聊天与接口能力全景展示
汇编·微信·企业微信·ipad
ZC跨境爬虫1 天前
【零基础实战】Fiddler抓取PC微信小程序数据流,爬取华为商城商品配置+真实评论(完整可运行代码+逐行解析)
测试工具·微信小程序·fiddler
S1998_1997111609•X1 天前
k:file/~*…/code/*iOS/an/app-/log in/ext./-system.API/-(NFV)=sdk.
数据库·网络协议·百度·微信·ssh
wechatbot8883 天前
企业微信 iPad 协议客服机器人自动化管理平台开发指南
java·运维·微信·自动化·企业微信·ipad
lichenyang4533 天前
从零到一:用 Taro + React 搭建数据采集小程序
react.js·小程序·taro
Gerardisite4 天前
私域运营新利器:RPA驱动外部群多模态互动
java·人工智能·python·微信·自动化