微信小程序+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" /> 
		</>
	)
}
相关推荐
蜗牛前端2 天前
codex 全流程开发上线的高颜值礼簿小程序
前端·微信小程序
爱勇宝6 天前
我想认真做一件小事:让孩子和家长更好地互动
微信小程序·小程序·云开发
唯火锅不可辜负6 天前
避坑指南:iOS 下 scroll-view 嵌套 fixed 布局的“翻车”现场与修复
微信小程序
didiplus6 天前
运维人的随身神器:我把25个常用工具塞进了微信小程序
微信小程序
张居斜7 天前
Obsidian + Claude Code + 微信AI,我把这三个系统缝进了一个软件
微信·obsidian·claude code·molio
一份执念7 天前
uni-app 小程序分包限制处理与主包体积优化实战
前端·微信小程序
一份执念7 天前
ECharts 安装与使用完全指南:从全量引入到小程序分包优化
微信小程序·echarts
skiyee8 天前
🔥UniApp 仅需 5 行代码!实现所有页面中控制应用主题变化
前端·微信小程序
Jinkey9 天前
要用户手机号真的是为了打骚扰电话吗?浅谈微信生态会员账号体系与资产合并
后端·微信·微信小程序
用户43242810611411 天前
微信小程序从0到1接入微信支付的完整攻略
微信小程序