taro 学习

527 阅读3分钟

小知识,大挑战!本文正在参与“  程序员必备小知识  ”创作活动

本文同时参与 「掘力星计划」  ,赢取创作大礼包,挑战创作激励金

一、安装

cnpm i -g @tarojs/cli

二、初始化项目

taro init myTaroProject

三、启动项目

npm run dev:h5 npm run dev:weapp

四、项目目录(taro 1版本)

image.png

五、生命周期

componentWillMount 在微信小程序中这一生命周期方法对应页面的onLoad或入口文件app中的onLaunch

componentDidMount 在微信小程序中这一生命周期方法对应页面的onReady或入口文件app中的onLaunch,在 componentWillMount后执行

componentDidShow 在微信小程序中这一生命周期方法对应 onShow

componentDidHide 在微信小程序中这一生命周期方法对应 onHide

componentDidCatchError 错误监听函数,在微信小程序中这一生命周期方法对应 onError

componentDidNotFound 页面不存在监听函数,在微信小程序中这一生命周期方法对应 onPageNotFound

shouldComponentUpdate 页面是否需要更新

componentWillUpdate 页面即将更新

componentDidUpdate 页面更新完毕

componentWillUnmount 页面退出,在微信小程序中这一生命周期方法对应 onUnload

在小程序中 ,页面还有一些专属的方法成员,如下:

  1. onPullDownRefresh: 页面相关事件处理函数–监听用户下拉动作

  2. onReachBottom: 页面上拉触底事件的处理函数

  3. onShareAppMessage: 用户点击右上角转发

  4. onPageScroll: 页面滚动触发事件的处理函数

  5. onTabItemTap: 当前是 tab 页时,点击 tab 时触发

  6. componentWillPreload: 预加载,只在微信小程序中可用 注意 1.通常入口文件会包含一个 config 配置项,这里的配置主要参考微信小程序的全局配置而来,在编译成小程序时,这一部分配置将会被抽离成 app.json,而编译成其他端,亦会有其他作用。

2.入口文件继承自 Component 组件基类,它同样拥有组件生命周期,但因为入口文件的特殊性,他的生命周期并不完整,如:componentWillMount、componentDidMount、componentDidShow、componentDidHide、componentDidCatchError、componentDidNotFound。

3.入口文件需要包含一个 render 方法,一般返回程序的第一个页面,但值得注意的是不要在入口文件中的 render 方法里写逻辑及引用其他页面、组件,因为编译时 render 方法的内容会被直接替换掉,你的逻辑代码不会起作用。

4.Taro 支持组件化开发,组件代码可以放在任意位置,不过建议放在 src 下的 components 目录中。一个组件通常包含组件 JS 文件以及组件样式文件,组织方式与页面类似。

六、路由

  1. 传递参数:
Taro.navigateTo({url:'/pages/index/index?name=3'})

接收参数:

const {name} = getCurrentInstance().router.params
  1. 重定向:
Taro.redirectTo({url:'/pages/index/index'}) //没有历史记录
  1. navigateBack与navigateTo到页面不会刷新(即不会重新请求接口),而redirectTo会的,但redirectTo没有历史记录,所以根据场景定方案
// Taro.navigateBack() //返回之后页面不会重新调用接口 
// Taro.navigateTo({ url: '/pages/user/index' }) 
//返回之后页面不会重新调用接口,此时返回会到本页面 
Taro.redirectTo({ url: '/pages/user/index' })

七、引用图片

<Image src={require('../../image/eslint3.png')}/> // 需要用require引入

或者

import img from '../../image/beatiful.jpg'; <Image src={img} />

八、children

this.props.children 获取子元素内容

九、事件处理

  1. 通过bind绑定this,
  2. event为最后一个参数,用event.stopPropagation阻止冒泡
<Button
  onClick={this.handleArgumentsClick.bind(
    this,
    this.state.name,
    'test'
  )}
>
  点击
</Button>

方法2:

  1. 通过箭头绑定this
  2. jsx里传入e参数
<Button
  onClick={(e) => this.handleArgumentsClick(this.state.name, 'test', e)}
>
  点击2
</Button>
handleArgumentsClick(name, test, event) { event.stopPropagation() }

十、storage

function setStorage(key, value) {
  let str = value
  if (typeof str == 'object') {
    str = JSON.stringify(str)
  }
  Taro.setStorageSync(key, str)
}
function getStorage(key) {
  let str = Taro.getStorageSync(key)
  if (!str) {
    return []
  }
  return JSON.parse(str)
}