微信小程序+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" /> 
		</>
	)
}
相关推荐
是一碗螺丝粉5 小时前
拯救你的app/小程序审核!一套完美避开审核封禁的URL黑名单机制
前端·javascript·微信小程序
我叫黑大帅13 小时前
微信小程序分包:告别加载慢,像拆快递一样简单!
前端·微信小程序
两个月菜鸟16 小时前
vue+微信小程序 五角星
前端·vue.js·微信小程序
摸着石头过河的石头1 天前
taro3.x-4.x路由拦截如何破?
前端·taro
熬耶1 天前
Uniapp之微信小程序自定义底部导航栏形态
微信小程序·小程序·uni-app
JohnYan2 天前
工作笔记 - 一次微信认证集成迁移
后端·安全·微信
誰在花里胡哨2 天前
微信小程序实现陀螺仪卡片景深效果
前端·微信小程序·动效
XXXFIRE2 天前
微信小程序开发实战笔记:全流程梳理
前端·微信小程序
Thomas游戏开发2 天前
Cocos Creator 面试技巧分享
面试·微信小程序·cocos creator
小小愿望3 天前
微信小程序开发实战:图片转 Base64 全解析
前端·微信小程序