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

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

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

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

switchAccountBehaviors.js:

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

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

import switchAccountBehaviors from "@/behaviors/switchAccountBehaviors";

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

Taro 页面的 index.config.js:

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


Taro 页面的 index.jsx



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

render() {
	...
	return (
		<>
			...
			<behaviors-component id="behaviors-component" /> 
		</>
	)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值