前言

记得16年底到17年初的时候,那时小程序刚出来,我也通过渠道获取了未正式发布的开发工具,准备一探究竟。结果看到一堆自创概率之后便望而却步。那时我狂热地追随 React,眼里哪还能容得下第二个框架。遂放弃。

2年多过去了,现在小程序如日中天,我不得不继续忽视它了(要恰饭的嘛),但是我好奇,为什么小程序会让我不爽,觉得不如 React,为什么 React 已经这么优秀和流行了,小程序不仿照它呢?遂作此文,记录下开发过程遇到的问题与思考。

在写这篇文章的时候,我力求不谈谁更先进,只谈谁更好用。

1. 组件自定义函数

在 React 中,构建组件采用的是类的方式,而小程序是对象方式。

// React 写法class Table extends Component {  method1() {    console.log(this.attr1);  }  method2() {    this.method1();  }}// 小程序写法Component({  methods: {    method1() {      console.log(this.attr1);    },    method2() {      this.method1();    },  },});

1. 概念问题

两者组件自定义方法都会被挂到 this 下。这点 React 很明显,就是 js 语法,没有学习成本。但是在小程序中,由于构造函数(Component)的不透明性,方法被挂到 this 下这点就必须灌输给用户。

2. 绑定问题

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);  }});

持续更新中,未完待续...