小程序缺陷和弥补方案
文章目录
前言
记得16年底到17年初的时候,那时小程序刚出来,我也通过渠道获取了未正式发布的开发工具,准备一探究竟。结果看到一堆自创概念,还不支持 npm 之后便望而却步。那时我狂热地追随 React,眼里哪还能容得下第二个框架。遂放弃。
2年多过去了,现在小程序如日中天,我无法再继续忽视它了(要恰饭的嘛),但是我好奇,为什么小程序会让我不爽,觉得不如 React,为什么 React 已经这么优秀和流行了,小程序不仿照它呢?遂作此文,记录下开发过程遇到的问题与思考。
在写这篇文章的时候,我力求不谈谁更先进,只谈谁更好用。
组件
自定义函数
在 React 中,构建组件采用的是类的方式,而小程序是对象方式。
// React 写法
class Table extends Component {
method1() {
console.log(this.attr1);
}
method2() {
this.method1();
}
}
// 小程序写法
Component({
methods: {
method1() {
console.log(this.attr1);
},
method2() {
this.method1();
},
},
});
概念问题
两者组件自定义方法都会被挂到 this 下。这点 React 很明显,就是 js 语法,没有学习成本。但是在小程序中,由于构造函数(Component)的不透明性,方法被挂到 this 下这点就必须灌输给用户。
绑定问题
React 中需要绑定函数 this 的话,可以在 constructor 中处理,类似的,小程序可以在 created 生命周期中处理。但是 React 中还有一种骚写法,就是改写为箭头函数来完成 this 绑定,这个在小程序中是做不到的。
// React 写法
class Table extends Component {
constructor(props) {
super(props);
// 显式 bind
this.method1 = this.method1.bind(this);
}
method1() {
console.log(this.attr1);
}
// React 的骚写法:箭头函数
method2 = () => {
this.method1();
};
}
// 小程序写法
Component({
methods: {
method1() {
console.log(this.attr1);
},
method2() {
this.method1();
},
},
created() {
// 只能显式 bind
this.method1 = this.method1.bind(this);
this.method2 = this.method2.bind(this);
}
});
如果是组件数据的函数绑定,就是下面这种写法。区别在于,React 的函数绑定是在初始化阶段完成的,而小程序必须在 ready 生命周期中,活生生推迟了绑定时机,并且多了一次无意义的渲染。
function method() {
console.log(this);
}
// React 写法
class Table extends Component {
constructor(props) {
super(props);
// 显式 bind
this.state.obj = {
method: method.bind(this);
};
}
}
// 小程序写法
Component({
ready() {
// 显式 bind
this.setData({
obj: {
method: method.bind(this),
},
});
}
});
properties 和 data 不分
进一步提升理解成本,冲突有潜在风险,如何处理(待调研)?
properties 不支持 function
React 中的常规操作,在小程序里只能借助 triggerEvent 来曲线救国。
模块管理
npm
必须写 index
其它
- wxml 中节点属性可以写成连字符形式(如
hover-class)或者驼峰形式(如hoverClass),在对应 js 中统一使用驼峰形式,不能说不好,但是也无形增加学习成本。
持续更新中,未完待续...
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论