1. 程式人生 > >taro框架的缺陷以及注意事項

taro框架的缺陷以及注意事項

https://www.jianshu.com/p/9d3318f7f219

1.不要使用 eval()

2.

禁止使用 Object 構造器

let config = new Object()   // ✗ 錯誤

 

3.

不使用 Generator 函式語法

使用 Promise 或者 async functions 來實現非同步程式設計

function* helloWorldGenerator() {     // ✗ 錯誤
  yield 'hello';
  yield 'world';
  return 'ending';
}

4.

SX 屬性均使用單引號

import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'

class MyComponent extends Component {
  render () {
    return (
      <View className='test'>     // ✓ 正確
        <Text className="test_text">12</Text>     // ✗ 錯誤
      </View>
    )
  }
}

5.

推薦使用物件解構的方式來使用 state、props

import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'

class MyComponent extends Component {
  state = {
    myTime: 12
  }
  render () {
    const { isEnable } = this.props     // ✓ 正確
    const { myTime } = this.state     // ✓ 正確
    return (
      <View className='test'>
        {isEnable && <Text className='test_text'>{myTime}</Text>}
      </View>
    )
  }
}

6.

不要以 class/id/style 作為自定義元件的屬性名

<Hello class='foo' />     // ✗ 錯誤
<Hello id='foo' />     // ✗ 錯誤
<Hello style='foo' />     // ✗ 錯誤

7.

不要在呼叫 this.setState 時使用 this.state

由於 this.setState 非同步的緣故,這樣的做法會導致一些錯誤,可以通過給 this.setState 傳入函式來避免

this.setState({
  value: this.state.value + 1
})   // ✗ 錯誤


this.setState(prevState => ({ value: prevState.value + 1 }))    // ✓ 正確

8.

map 迴圈時請給元素加上 key 屬性

list.map(item => {
  return (
    <View className='list_item' key={item.id}>{item.name}</View>
  )
})

9.

儘量避免在 componentDidMount 中呼叫 this.setState

因為在 componentDidMount 中呼叫 this.setState 會導致觸發更新

import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'

class MyComponent extends Component {
  state = {
    myTime: 12
  }
  
  componentDidMount () {
    this.setState({     // ✗ 儘量避免,可以在 componentWillMount 中處理
      name: 1
    })
  }
  
  render () {
    const { isEnable } = this.props
    const { myTime } = this.state
    return (
      <View className='test'>
        {isEnable && <Text className='test_text'>{myTime}</Text>}
      </View>
    )
  }
}

10.

不要在 componentWillUpdate/componentDidUpdate/render 中呼叫 this.setState

import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'

class MyComponent extends Component {
  state = {
    myTime: 12
  }
  
  componentWillUpdate () {
    this.setState({     // ✗ 錯誤
      name: 1
    })
  }
  
  componentDidUpdate () {
    this.setState({     // ✗ 錯誤
      name: 1
    })
  }
  
  render () {
    const { isEnable } = this.props
    const { myTime } = this.state
    this.setState({     // ✗ 錯誤
      name: 11
    })
    return (
      <View className='test'>
        {isEnable && <Text className='test_text'>{myTime}</Text>}
      </View>
    )
  }
}

不要定義沒有用到的 state

 

11.

元件最好定義 defaultProps

import Taro, { Component } from '@tarojs/taro'
import { View, Input } from '@tarojs/components'

class MyComponent extends Component {

  static defaultProps = {
    isEnable: true
  }
  
  state = {
    myTime: 12
  }
  
  render () {
    const { isEnable } = this.props
    const { myTime } = this.state

    return (
      <View className='test'>
        {isEnable && <Text className='test_text'>{myTime}</Text>}
      </View>
    )
  }
}

12.taro注意:

不能在包含 JSX 元素的 map 迴圈中使用 if 表示式

以下程式碼會被 ESLint 提示警告,同時在 Taro(小程式端)也不會有效:

numbers.map((number) => {
  let element = null
  const isOdd = number % 2
  if (isOdd) {
    element = <Custom />
  }
  return element
})

以下程式碼不會被警告,也應當在 Taro 任意端中能夠執行:

numbers.map((number) => {
  let isOdd = false
  if (number % 2) {
    isOdd = true
  }
  return isOdd && <Custom />
})

 

13.

儘量在 map 迴圈中使用條件表示式或邏輯表示式

numbers.map((number) => {
  const isOdd = number % 2
  return isOdd ? <Custom /> : null
})

numbers.map((number) => {
  const isOdd = number % 2
  return isOdd && <Custom />
})

 

14不能使用 Array#map 之外的方法操作 JSX 陣列

15.

先處理好需要遍歷的陣列,然後再用處理好的陣列呼叫 map 方法。

numbers.filter(isOdd).map((number) => <View />)

for (let index = 0; index < array.length; index++) {
  // do you thing with array
}

const element = array.map(item => {
  return <View />
})

 

16.

不能在 JSX 引數中使用匿名函式

以下程式碼會被 ESLint 提示警告,同時在 Taro(小程式端)也不會有效:

<View onClick={() => this.handleClick()} />

<View onClick={(e) => this.handleClick(e)} />

<View onClick={() => ({})} />

<View onClick={function () {}} />

<View onClick={function (e) {this.handleClick(e)}} />

 

17.

以下程式碼不會被警告,也應當在 Taro 任意端中能夠執行:

<View onClick={this.hanldeClick} />

<View onClick={this.props.hanldeClick} />

<View onClick={this.hanldeClick.bind(this)} />

<View onClick={this.props.hanldeClick.bind(this)} />

 

18

不能在 JSX 引數中使用物件展開符

以下程式碼會被 ESLint 提示警告,同時在 Taro(小程式端)也不會有效:

<View {...this.props} />

<View {...props} />

<Custom {...props} />

 

19

不支援無狀態元件

以下程式碼會被 ESLint 提示警告,同時在 Taro(小程式端)也不會有效:

function Test () {
  return <View />
}

function Test (ary) {
  return ary.map(() => <View />)
}

const Test = () => {
  return <View />
}

const Test = function () {
  return <View />
}

 

20

微信小程式中 onLaunch 通常帶有一個引數 options,在 Taro 中你可以在所有生命週期和普通事件方法中通過 this.$router.params 訪問到,在其他端也適用

21 render中不要寫邏輯

22.

路由傳參

我們可以通過在所有跳轉的 url 後面新增查詢字串引數進行跳轉傳參,例如

// 傳入引數 id=2&type=test
Taro.navigateTo({
  url: '/pages/page/path/name?id=2&type=test'
})

這樣的話,在跳轉成功的目標頁的生命週期方法裡就能通過 this.$router.params 獲取到傳入的引數,例如上述跳轉,在目標頁的 componentWillMount 生命週期裡獲取入參

class C extends Taro.Component {
  componentWillMount () {
    console.log(this.$router.params) // 輸出 { id: 2, type: 'test' }
  }
}

23

在 Taro 中尺寸單位建議使用 px、 百分比 %,Taro 預設會對所有單位進行轉換。在 Taro 中書寫尺寸按照 1:1 的關係來進行書寫,即從設計稿上量的長度 100px,那麼尺寸書寫就是 100px,當轉成微信小程式的時候,尺寸將預設轉換為 100rpx,當轉成 H5 時將預設轉換為以 rem 為單位的值。

如果你希望部分 px 單位不被轉換成 rpx 或者 rem ,最簡單的做法就是在 px 單位中增加一個大寫字母,例如 Px 或者 PX 這樣,則會被轉換外掛忽略。

結合過往的開發經驗,Taro 預設以 750px 作為換算尺寸標準,如果設計稿不是以 750px 為標準,則需要在專案配置 config/index.js 中進行設定,例如設計稿尺寸是 640px,則需要修改專案配置 config/index.js 中的 designWidth配置為 640

const config = {
  projectName: 'myProject',
  date: '2018-4-18',
  designWidth: 640,
  ....
}

目前 Taro 支援 750、 640 、 828 三種尺寸設計稿,他們的換算規則如下:

const DEVICE_RATIO = {
  '640': 2.34 / 2,
  '750': 1,
  '828': 1.81 / 2
}

24.

小程式樣式中引用本地資源

在小程式的樣式中,預設不能直接引用本地資源,只能通過網路地址、Base64 的方式來進行資源引用,為了方便開發,Taro 提供了直接在樣式檔案中引用本地資源的方式,其原理是通過 PostCSS 的 postcss-url 外掛將樣式中本地資源引用轉換成 Base64 格式,從而能正常載入。

Taro 預設會對 10kb 大小以下的資源進行轉換,如果需要修改配置,可以在 config/index.js 中進行修改,配置位於 weapp.module.postcss

具體配置如下

// 小程式端樣式引用本地資源內聯
url: {
  enable: true,
  config: {
    limit: 10240 // 設定轉換尺寸上限
  }
}

25

JavaScript 表示式也可以巢狀:

render () {
  const todos = ['finish doc', 'submit pr', 'nag dan to review'];
  return (
    <ul>
      {todos.map((todo) => <Text>{todo}</Text>)}
    </ul>
  )
}

26 條件判斷

<View> {showHeader && <Header />} <Content /> </View> 

27

使用 PropTypes 檢查型別

隨著應用日漸龐大,你可以通過型別檢查捕獲大量錯誤。要檢查元件的屬性,你需要配置特殊的 propTypes 屬性:

import PropTypes from 'prop-types';

class Greeting extends Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}

Greeting.propTypes = {
  name: PropTypes.string
};

如上例,Taro 與 React 一樣,也支援PropTypes 檢查型別,目前在小程式端還有些問題,但在 H5 端可以使用,用法和在 React 裡一樣。 更多可參照React 的相關文件

28

setState非同步

// 假設我們之前設定了 this.state.counter = 0
updateCounter () {
  this.setState({
    counter: 1
  }, () => {
    // 在這個函式內你可以拿到 setState 之後的值
  })
}

 

 

29

在 Taro 中另一個不同是你不能使用 catchEvent 的方式阻止事件冒泡。你必須明確的使用 stopPropagation。例如,阻止事件冒泡你可以這樣寫:

class Toggle extends React.Component {
  constructor (props) {
    super(props)
    this.state = {isToggleOn: true}
  }

  onClick = (e) => {
    e.stopPropagation()
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }))
  }

  render () {
    return (
      <button onClick={this.onClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    )
  }
}

30

向事件處理程式傳遞引數

通常我們會為事件處理程式傳遞額外的引數。例如,若是 id 是你要刪除那一行的 id,以下兩種方式都可以向事件處理程式傳遞引數:

<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

31

當你通過 bind 方式向監聽函式傳參,在類元件中定義的監聽函式,事件物件 e 要排在所傳遞引數的後面。

class Popper extends Component {
  constructor () {
    super(...arguments)
    this.state = { name:'Hello world!' }
  }

  // 你可以通過 bind 傳入多個引數
  preventPop (name, test, e) {    //事件物件 e 要放在最後
    e.preventDefault()
  }

  render () {
    return <Button onClick={this.preventPop.bind(this, this.state.name, 'test')}></Button>
  }
}

32

父元件控制狀態值來決定子元件的條件渲染

33

Keys

但是在上面的程式碼,你會得到一個報錯:提醒你當迴圈一個數組時應該提供 keys。Keys 可以在 DOM 中的某些元素被增加或刪除的時候幫助 Nerv/小程式 識別哪些元素髮生了變化。因此你應當給陣列中的每一個元素賦予一個確定的標識。

const numbers = [...Array(100).keys()] // [0, 1, 2, ..., 98, 99]
const listItems = numbers.map((number) => {
  return <Text
    key={String(number)}
    class='li'
    >
    我是第 {number + 1} 個數字
  </Text>
})

34不同陣列中可以使用相同的key

陣列元素中使用的 key 在其兄弟之間應該是獨一無二的。然而,它們不需要是全域性唯一的。當我們生成兩個不同的陣列時,我們可以使用相同的 key:

class App extends Componenet {
  state = {
    posts: [
      {id: 1, title: 'Hello World', content: 'Welcome to learning Taro!'},
      {id: 2, title: 'Installation', content: 'You can install Taro from npm.'}
    ]
  }
  render () {
    const { posts } = this.state
    const sidebar = (
      <View>
        {posts.map((post) =>
          <Text key={post.id}>
            {post.title}
          </Text>
        )}
      </View>
    )
    const content = posts.map((post) => {
      return <View key={post.id}>
        <Text>{post.title}</Text>
        <Text>{post.content}</Text>
      </View>
    })
    return (
      <View>
        {sidebar}
        <View class="divider" />
        {content}
      </View>
    )
  }
}

35

Children

在我們設計元件時,有些元件通常不知道自己的子元件會有什麼內容,例如 Sidebar 和 Dialog 這樣的容器元件。

我們建議在這樣的情況使用 this.props.children 來傳遞子元素:

class Dialog extends Component {
  render () {
    return (
      <View className='dialog'>
        <View className='header'>Welcome!</View>
        <View className='body'>
          {this.props.children}
        </View>
        <View className='footer'>-- divider --</View>
      </View>
    )
  }
}

這樣就能允許其它元件在 JSX 中巢狀任意子元件傳遞給 Dialog:

class App extends Component {
  render () {
    return (
      <View className='container'>
        <Dialog>
          <View className="dialog-message">
            Thank you for using Taro.
          </View>
        </Dialog>
      </View>
    )
  }
}

在 <Dialog /> JSX 標籤內的任何內容都會作為它的子元素(Children)都會傳遞到它的元件。

36  refs   rechart 元素繫結初始化

class MyComponent extends Component { componentDidMount () { // 如果 ref 的是小程式原生元件,那只有在 didMount 生命週期之後才能通過 // this.refs.input 訪問到小程式原生元件 if (process.env.TARO_ENV === 'weapp') { // 這裡 this.refs.input 訪問的時候通過 `wx.createSeletorQuery` 取到的小程式原生元件 } else if (process.env.TARO_ENV === 'h5') { // 這裡 this.refs.input 訪問到的是 `@tarojs/components` 的 `Input` 元件例項 } } render () { return <Input ref='input' /> } } 

37

利用 externalClasses 定義段定義若干個外部樣式類。這個特性從小程式基礎庫版本 1.9.90 開始支援。

/* CustomComp.js */
export default CustomComp extends Component {
  static externalClasses = ['my-class']

  render () {
    return <View className="my-class">這段文字的顏色由元件外的 class 決定</View>
  }
}
/* MyPage.js */
export default MyPage extends Component {
  render () {
    return <CustomComp my-class="red-text" />
  }
}
/* MyPage.scss */
.red-text {
  color: red;
}

38

全域性樣式類

使用外部樣式類可以讓元件使用指定的元件外樣式類,如果希望元件外樣式類能夠完全影響元件內部,可以將元件構造器中的 options.addGlobalClass 欄位置為 true。這個特性從小程式基礎庫版本 2.2.3 開始支援。

/* CustomComp.js */
export default CustomComp extends Component {
  static options = {
    addGlobalClass: true
  }

  render () {
    return <View className="red-text">這段文字的顏色由元件外的 class 決定</View>
  }
}
/* 元件外的樣式定義 */
.red-text {
  color: red;
}

 

39

使用 this.$componentType 來判斷當前 Taro.Component 是頁面還是元件

40

this.$componentType 可能取值分別為 PAGE 和 COMPONENT,開發者可以根據此變數的取值分別採取不同邏輯。

 

41

微信小程式中,從呼叫 Taro.navigateToTaro.redirectTo 或 Taro.switchTab 後,到頁面觸發 componentWillMount 會有一定延時。因此一些網路請求可以提前到發起跳轉前一刻去請求。

Taro 提供了 componentWillPreload 鉤子,它接收頁面跳轉的引數作為引數。可以把需要預載入的內容通過 return 返回,然後在頁面觸發 componentWillMount 後即可通過 this.$preloadData 獲取到預載入的內容。

class Index extends Component {
  componentWillMount () {
    console.log('isFetching: ', this.isFetching)
    this.$preloadData
      .then(res => {
        console.log('res: ', res)
        this.isFetching = false
      })
  }

  componentWillPreload (params) {
    return this.fetchData(params.url)
  }

  fetchData () {
    this.isFetching = true
    ...
  }
}

 

42

預載入

微信小程式中,從呼叫 Taro.navigateToTaro.redirectTo 或 Taro.switchTab 後,到頁面觸發 componentWillMount 會有一定延時。因此一些網路請求可以提前到發起跳轉前一刻去請求。

Taro 提供了 componentWillPreload 鉤子,它接收頁面跳轉的引數作為引數。可以把需要預載入的內容通過 return 返回,然後在頁面觸發 componentWillMount 後即可通過 this.$preloadData 獲取到預載入的內容。

class Index extends Component {
  componentWillMount () {
    console.log('isFetching: ', this.isFetching)
    this.$preloadData
      .then(res => {
        console.log('res: ', res)
        this.isFetching = false
      })
  }

  componentWillPreload (params) {
    return this.fetchData(params.url)
  }

  fetchData () {
    this.isFetching = true
    ...
  }
}

 

 

43 全域性變數

全域性變數

在 Taro 中推薦使用 Redux 來進行全域性變數的管理,但是對於一些小型的應用, Redux 就可能顯得比較重了,這時候如果想使用全域性變數,推薦如下使用。

新增一個自行命名的 JS 檔案,例如 global_data.js,示例程式碼如下

const globalData = {}

export function set (key, val) {
  globalData[key] = val
}

export function get (key) {
  return globalData[key]
}

隨後就可以在任意位置進行使用啦

import { set as setGlobalData, get as getGlobalData } from './path/name/global_data'

setGlobalData('test', 1)

getGlobalData('test')

44 上傳下載

上傳、下載

Taro.uploadFile(OBJECT)

使用方式同 wx.uploadFile,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

const uploadTask = Taro.uploadFile(params).then(...)

Taro.downloadFile(OBJECT)

使用方式同 wx.downloadFile,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.downloadFile(params).then(...)

 

45 端能力api

圖片

Taro.chooseImage(OBJECT)

使用方式同 wx.chooseImage,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.chooseImage(params).then(...)

Taro.previewImage(OBJECT)

使用方式同 wx.previewImage,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.previewImage(params).then(...)

Taro.getImageInfo(OBJECT)

使用方式同 wx.getImageInfo,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.getImageInfo(params).then(...)

Taro.saveImageToPhotosAlbum(OBJECT)

使用方式同 wx.saveImageToPhotosAlbum,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.saveImageToPhotosAlbum(params).then(...)
 
 

46 端能力api

Taro.showToast(OBJECT)

Taro.showToast({ title: '成功', icon: 'success', duration: 2000 }) .then(res => console.log(res))

Taro.showLoading(OBJECT)

顯示 loading 提示框, 需主動呼叫 Taro.hideLoading 才能關閉提示框,支援 Promise 化使用。

OBJECT 引數說明:

引數 型別 必填 說明
title String 提示的內容
mask Boolean 是否顯示透明蒙層,防止觸控穿透,預設:false
success Function 介面呼叫成功的回撥函式
fail Function 介面呼叫失敗的回撥函式
complete Function 介面呼叫結束的回撥函式(呼叫成功、失敗都會執行)

示例程式碼:

import Taro from '@tarojs/taro'

Taro.showLoading({
  title: 'loading'
})
  .then(res => console.log(res))

Taro.hideToast()

隱藏訊息提示框

Taro.hideLoading()

隱藏 loading 提示框

Taro.showModal(OBJECT)

import Taro from '@tarojs/taro' // 注意:無論使用者點選確定還是取消,Promise 都會 resolve。 Taro.showModal({ title: 'xxx', content: 'hello world', }) .then(res => console.log(res.confirm, res.cancel))

 

Taro.showActionSheet(OBJECT)

顯示操作選單,支援 Promise 化使用。

 

設定導航條

Taro.setNavigationBarTitle(OBJECT)

使用方式同 wx.setNavigationBarTitle,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.setNavigationBarTitle(params).then(...)

Taro.showNavigationBarLoading()

在當前頁面顯示導航條載入動畫。

Taro.hideNavigationBarLoading()

隱藏導航條載入動畫。

Taro.setNavigationBarColor(OBJECT)

使用方式同 wx.setNavigationBarColor,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.setNavigationBarColor(params).then(...)

API 支援度

API 微信小程式 H5 ReactNative
Taro.setNavigationBarTitle ✔️   ✔️
Taro.showNavigationBarLoading ✔️   ✔️
Taro.hideNavigationBarLoading ✔️   ✔️
Taro.setNavigationBarColor ✔️   ✔️(不支援 animation 引數)

設定 tabBar

Taro.setTabBarBadge(OBJECT)

使用方式同 wx.setTabBarBadge,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.setTabBarBadge(params).then(...)

Taro.removeTabBarBadge(OBJECT)

使用方式同 wx.removeTabBarBadge,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.removeTabBarBadge(params).then(...)

Taro.showTabBarRedDot(OBJECT)

使用方式同 wx.showTabBarRedDot,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.showTabBarRedDot(params).then(...)

Taro.hideTabBarRedDot(OBJECT)

使用方式同 wx.hideTabBarRedDot,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.hideTabBarRedDot(params).then(...)

Taro.setTabBarStyle(OBJECT)

使用方式同 wx.setTabBarStyle,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.setTabBarStyle(params).then(...)

Taro.setTabBarItem(OBJECT)

使用方式同 wx.setTabBarItem,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.setTabBarItem(params).then(...)

Taro.showTabBar(OBJECT)

使用方式同 wx.showTabBar,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.showTabBar(params).then(...)

Taro.hideTabBar(OBJECT)

使用方式同 wx.hideTabBar,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.hideTabBar(params).then(...)

API 支援度

API 微信小程式 H5 ReactNative
Taro.setTabBarBadge ✔️    
Taro.removeTabBarBadge ✔️    
Taro.showTabBarRedDot ✔️    
Taro.hideTabBarRedDot ✔️    
Taro.setTabBarStyle ✔️    
Taro.setTabBarItem ✔️    
Taro.showTabBar ✔️    
Taro.hideTabBar ✔️    

設定置頂資訊

Taro.setTopBarText(OBJECT)

使用方式同 wx.setTopBarText,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.setTopBarText(params).then(...)

API 支援度

API 微信小程式 H5 ReactNative
Taro.setTopBarText ✔️    

導航

Taro.navigateTo(OBJECT)

使用方式同 wx.navigateTo,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.navigateTo(params).then(...)

Taro.redirectTo(OBJECT)

使用方式同 wx.redirectTo,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.redirectTo(params).then(...)

Taro.switchTab(OBJECT)

使用方式同 wx.switchTab,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.switchTab(params).then(...)

Taro.navigateBack(OBJECT)

使用方式同 wx.navigateBack

示例程式碼:

import Taro from '@tarojs/taro'

Taro.navigateBack({ delta: 2 })

Taro.reLaunch(OBJECT)

使用方式同 wx.reLaunch,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.reLaunch(params).then(...)

Taro.getCurrentPages(OBJECT)

使用方式同 getCurrentPages, 獲取當前的頁面棧,決定需要返回幾層。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.getCurrentPages().length

API 支援度

API 微信小程式 H5 ReactNative
Taro.navigateTo ✔️ ✔️ ✔️
Taro.redirectTo ✔️ ✔️ ✔️
Taro.switchTab ✔️   ✔️
Taro.navigateBack ✔️ ✔️ ✔️
Taro.reLaunch ✔️   ✔️  
Taro.getCurrentPages ✔️   ✔️

動畫

Taro.createAnimation(OBJECT)

使用方式同 wx.createAnimation

示例程式碼:

import Taro from '@tarojs/taro'

const animation = Taro.createAnimation({
  transformOrigin: "50% 50%",
  duration: 1000,
  timingFunction: "ease",
  delay: 0
})

API 支援度

API 微信小程式 H5 ReactNative
Taro.createAnimation ✔️    

位置

Taro.pageScrollTo(OBJECT)

使用方式同 wx.pageScrollTo,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.pageScrollTo(params).then(...)

API 支援度

API 微信小程式 H5 ReactNative
Taro.pageScrollTo ✔️    

繪圖

Taro.createCanvasContext(canvasId, this.$scope)

使用方式同 wx.createCanvasContext

Taro.createContext(不推薦使用)

建立並返回繪圖上下文。

Taro.drawCanvas(不推薦使用)

使用方式同 wx.drawCanvas

API 支援度

API 微信小程式 H5 ReactNative
Taro.createCanvasContext ✔️    
Taro.createContext ✔️    
Taro.drawCanvas ✔️    

下拉重新整理

Taro.startPullDownRefresh(OBJECT)

使用方式同 wx.startPullDownRefresh,支援 Promise 化使用。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.startPullDownRefresh(params).then(...)

Taro.stopPullDownRefresh()

停止當前頁面下拉重新整理。

示例程式碼:

import Taro from '@tarojs/taro'

Taro.stopPullDownRefresh()