微信小程序+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" /> 
		</>
	)
}
相关推荐
钱栈up4 小时前
王兴一句话释放美团AI「降温」信号:明年资本开支要压下来
微信
千寻技术帮12 小时前
基于微信小程序的家政服务系统(源码+脚本+文档)_50039
mysql·微信小程序·小程序·毕业设计·家政服务
愚公搬代码14 小时前
【愚公系列】《微信小程序项目实战(AI编程+视频图解)》045-项目实战:使用 AI 编程工具辅助实现我的订单页面
人工智能·微信小程序·ai编程
源码手记16 小时前
基于微信小程序的购物商城系统-毕设源码
微信小程序·小程序·课程设计
社会渣渣1 天前
开发者工具正常、真机白屏:一次渲染差异排查
微信小程序
daguanren2 天前
一个页面外壳,多页复用:weapp-vite / Wevu 布局的编译与动态切换
微信小程序
源码手记2 天前
基于微信小程序的上门代厨厨师预约系统-毕设源码
微信小程序·小程序·课程设计
千寻技术帮2 天前
基于微信小程序的点餐管理系统_50044(源码+脚本+文档)
mysql·微信小程序·小程序·毕业设计·springboot·点餐管理系统
wechatbot8882 天前
企业微信 API:通过接口二次开发将外部联系人转化为业务创造力的实战效果
微信·企业微信·企业微信scrm·企业微信api·企微外部联系人
极客互动API2 天前
企业微信 iPad 协议核心:外部联系人消息如何实时回调进业务系统
微信·企业微信·企微scrm·企业微信api·企微外部联系人