Taro 使用指南

2019-04-13  本文已影响0人  风之化身呀

Taro 就是可以用 React 语法写小程序的框架,拥有多端转换能力,一套代码可编译为微信小程序、百度小程序、支付宝小程序、H5、RN等

1、入门

1.1、安装 CLI 及项目初始化

npm install -g @tarojs/cli
taro init 项目名
Taro初始化项目.png

可以选择使用 SCSS 、TS、Redux

1.2、编译至各种平台

// 编译为小程序
npm run dev:weapp
npm run build:weapp
// 编译为 H5
npm run dev:h5
// 编译为 RN
npm run dev:rn

编译为小程序时,小程序代码位于 dist 目录下

1.3、微信小程序须知

2、注意点

-由于 Taro 编译后的代码已经经过了转义和压缩,因此还需要注意微信开发者工具的项目设置


微信开发者工具配置.png
<View {...props} />  // wrong
<View id={id} title={title} />  // ok

3、Taro实战

3.1、相关库介绍

import Taro, { Component } from '@tarojs/taro'
class App extends Component {}
Taro.render(<App />, document.getElementById('app'))
import { Provider,connect  } from '@tarojs/redux'
import { View, Button, Text } from "@tarojs/components";
<View className='index'>
   <Button className='add_btn' onClick={this.props.add}>
       +
   </Button>
   <Text> Hello, World </Text>
</View>
     import { AtTabs, AtTabsPane } from "taro-ui";
     <AtTabs
        current={this.state.current}
        tabList={tabList}
        onClick={this.handleClick.bind(this)}
      >
        <AtTabsPane current={this.state.current} index={0}>
          <AllContainer />
        </AtTabsPane>
        <AtTabsPane current={this.state.current} index={1}>
          <View style='padding: 100px 50px;background-color: #FAFBFC;text-align: center;'>
            标签页二的内容
          </View>
        </AtTabsPane>
        <AtTabsPane current={this.state.current} index={2}>
          <View style='padding: 100px 50px;background-color: #FAFBFC;text-align: center;'>
            标签页三的内容
          </View>
        </AtTabsPane>
      </AtTabs>

3.2、常用工具类封装

import Taro from "@tarojs/taro";

class Store {
  removeItem(key) {
    return Taro.removeStorageSync(key);
  }
  getItem(key) {
    return Taro.getStorageSync(key);
  }
  setItem(key, value) {
    return Taro.setStorageSync(key, value);
  }
  clear() {
    return Taro.clearStorageSync();
  }
}

export default  new Store();
import Taro from '@tarojs/taro'
import {
  API_USER_LOGIN
} from '@constants/api'

const CODE_SUCCESS = '200'
const CODE_AUTH_EXPIRED = '600'

function getStorage(key) {
  return Taro.getStorage({
    key
  }).then(res => res.data).catch(() => '')
}

function updateStorage(data = {}) {
  return Promise.all([
    Taro.setStorage({
      key: 'token',
      data: data['3rdSession'] || ''
    }),
    Taro.setStorage({
      key: 'uid',
      data: data['uid'] || ''
    })
  ])
}

/**
 * 简易封装网络请求
 * // NOTE 需要注意 RN 不支持 *StorageSync,此处用 async/await 解决
 * @param {*} options
 */
export default async function fetch(options) {
  const {
    url,
    payload,
    method = 'GET',
    showToast = true
  } = options
  const token = await getStorage('token')
  const header = token ? {
    'WX-PIN-SESSION': token,
    'X-WX-3RD-Session': token
  } : {}
  if (method === 'POST') {
    header['content-type'] = 'application/json'
  }

  return Taro.request({
    url,
    method,
    data: payload,
    header
  }).then(async (res) => {
    const {
      code,
      data
    } = res.data
    if (code !== CODE_SUCCESS) {
      if (code === CODE_AUTH_EXPIRED) {
        await updateStorage({})
      }
      return Promise.reject(res.data)
    }

    if (url === API_USER_LOGIN) {
      await updateStorage(data)
    }
    return data
  }).catch((err) => {
    const defaultMsg = err.code === CODE_AUTH_EXPIRED ? '登录失效' : '请求异常'
    if (showToast) {
      Taro.showToast({
        title: err && err.errorMsg || defaultMsg,
        icon: 'none'
      })
    }

    return Promise.reject({
      message: defaultMsg,
      ...err
    })
  })
}

3.3 常用API介绍

<Button
   className='btn-max-w'
   plain
   type='primary'
   open-type='getUserInfo'
   onGetUserInfo={this.handleUserInfo}
>
    授权
</Button>
Taro.getLocation({type:'gcj02 '}).then(data=>console.log(data))
   Taro.showToast({
      title: "成功",
      icon: "success"
    });

    Taro.setTabBarBadge({ index: 1, text: "1" });

    Taro.showLoading({
      title: "加载中..."
    }).then(res =>
      setTimeout(() => {
        Taro.hideLoading();
      }, 2000)
    );

4、其他问题记录

// app.scss
page {
  height: 100%;
}
        // css modules 功能开关与相关配置
        cssModules: {
          enable: true, // 默认为 false,如需使用 css modules 功能,则设为 true
          config: {
            namingPattern: 'module', // 转换模式,取值为 global/module,下文详细说明
            generateScopedName: '[name]__[local]___[hash:base64:5]'
          }
        }
alias: {
    'components': path.resolve(__dirname, '..', 'src/components'),
    'pages': path.resolve(__dirname, '..', 'src/pages'),
    'store': path.resolve(__dirname, '..', 'src/store'),
    'constants': path.resolve(__dirname, '..', 'src/constants'),
    'api': path.resolve(__dirname, '..', 'src/api'),
    'assets': path.resolve(__dirname, '..', 'src/assets'),
    'utils': path.resolve(__dirname, '..', 'src/utils'),
  },

4、个人开发的 TaroCnode 小程序

上一篇 下一篇

猜你喜欢

热点阅读