Taro 就是可以用 React 語法寫小程序的框架翅溺,擁有多端轉(zhuǎn)換能力脑漫,一套代碼可編譯為微信小程序、百度小程序咙崎、支付寶小程序优幸、H5、RN等
1褪猛、入門
1.1网杆、安裝 CLI 及項(xiàng)目初始化
npm install -g @tarojs/cli
taro init 項(xiàng)目名
Taro初始化項(xiàng)目.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新啼、微信小程序須知
- 小程序注冊
注冊地址追城,注意一個郵箱只能注冊一個小程序 - 小程序后臺
后臺地址,后臺可查看當(dāng)前小程序版本燥撞,添加開發(fā)者座柱,查看小程序 AppID 和 AppSecret 等功能 - 小程序開發(fā)者工具
下載地址 - 小程序開發(fā)流程
1、在開發(fā)者工具中新建項(xiàng)目物舒,填入對應(yīng)的AppID
2色洞、在小程序后臺配置服務(wù)器域名(開發(fā)-服務(wù)器域名) - 小程序發(fā)布流程
1、在開發(fā)者工具中上傳代碼
2冠胯、在管理后臺-版本管理-開發(fā)版本中提交審核火诸,注意提交審核前可先生成體驗(yàn)版,確認(rèn)體驗(yàn)版沒問題后再提交審核
2荠察、注意點(diǎn)
-由于 Taro 編譯后的代碼已經(jīng)經(jīng)過了轉(zhuǎn)義和壓縮置蜀,因此還需要注意微信開發(fā)者工具的項(xiàng)目設(shè)置
微信開發(fā)者工具配置.png
- 只能在render里使用JSX語法
- 不能在包含 JSX 元素的 map 循環(huán)中使用 if 表達(dá)式
盡量在 map 循環(huán)中使用條件表達(dá)式或邏輯表達(dá)式 - 不能使用 Array.map 之外的方法操作 JSX 數(shù)組
先處理好需要遍歷的數(shù)組,然后再用處理好的數(shù)組調(diào)用 map 方法悉盆。 - 不能在 JSX 參數(shù)中使用匿名函數(shù)
使用bind
或 類參數(shù)綁定函數(shù)盯荤。 - 不能在 JSX 參數(shù)中使用對象展開符
開發(fā)者自行賦值:
<View {...props} /> // wrong
<View id={id} title={title} /> // ok
- 不允許在 JSX 參數(shù)(props)中傳入 JSX 元素
- 不支持無狀態(tài)組件(Stateless Component)
- 函數(shù)名駝峰,且不能包含數(shù)字焕盟,不能以下劃線開始或結(jié)尾以及長度不超過20
- 必須使用單引號秋秤,不支持雙引號
- 對于process.env,建議直接書寫process.env.NODE_ENV,而不是解構(gòu)
- 組件傳遞函數(shù)屬性名以 on 開頭
- 小程序端不要將在模板中用到的數(shù)據(jù)設(shè)置為 undefined
- 小程序端不要在組件中打印 this.props.children
- 組件屬性傳遞注意
不要以 id灼卢、class绍哎、style 作為自定義組件的屬性與內(nèi)部 state 的名稱,因?yàn)檫@些屬性名在微信小程序中會丟失芥玉。 - 組件 state 與 props 里字段重名的問題
不要在 state 與 props 上用同名的字段蛇摸,因?yàn)檫@些被字段在微信小程序中都會掛在 data 上。 - 小程序中頁面生命周期 componentWillMount 不一致問題
- 組件的 constructor 與 render 提前調(diào)用
3灿巧、Taro實(shí)戰(zhàn)
3.1、相關(guān)庫介紹
- @tarojs/taro
taro 核心庫揽涮,相當(dāng)于 react
import Taro, { Component } from '@tarojs/taro'
class App extends Component {}
Taro.render(<App />, document.getElementById('app'))
- @tarojs/redux
taro 狀態(tài)管理輔助庫抠藕,相當(dāng)于 react-redux
import { Provider,connect } from '@tarojs/redux'
- @tarojs/components
taro 為屏蔽多端差異而制定的標(biāo)準(zhǔn)組件庫,在taro中不能直接寫常規(guī)的HTML標(biāo)簽蒋困,而必須用這個組件庫里的標(biāo)簽盾似,就像寫RN一樣:
import { View, Button, Text } from "@tarojs/components";
<View className='index'>
<Button className='add_btn' onClick={this.props.add}>
+
</Button>
<Text> Hello, World </Text>
</View>
- @tarojs/async-await
taro 支持 async await 寫法庫 - taro-ui
taro 為屏蔽多端差異而制定的業(yè)務(wù)組件庫,比如 Tabs雪标,Modal零院,Menu之類的常用的業(yè)務(wù)組件
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;'>
標(biāo)簽頁二的內(nèi)容
</View>
</AtTabsPane>
<AtTabsPane current={this.state.current} index={2}>
<View style='padding: 100px 50px;background-color: #FAFBFC;text-align: center;'>
標(biāo)簽頁三的內(nèi)容
</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'] || ''
})
])
}
/**
* 簡易封裝網(wǎng)絡(luò)請求
* // 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介紹
- 授權(quán)
<Button
className='btn-max-w'
plain
type='primary'
open-type='getUserInfo'
onGetUserInfo={this.handleUserInfo}
>
授權(quán)
</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告抄、其他問題記錄
- 設(shè)置頁面全屏
// app.scss
page {
height: 100%;
}
- Css Modules 支持
配置 config/index.js 下的 h5 和 weapp 中的 module.cssModules 即可
// css modules 功能開關(guān)與相關(guān)配置
cssModules: {
enable: true, // 默認(rèn)為 false,如需使用 css modules 功能嵌牺,則設(shè)為 true
config: {
namingPattern: 'module', // 轉(zhuǎn)換模式打洼,取值為 global/module,下文詳細(xì)說明
generateScopedName: '[name]__[local]___[hash:base64:5]'
}
}
- 配置路徑別名
配置 config/index.js 下的 alias
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逆粹、個人開發(fā)的 TaroCnode 小程序
- 代碼地址:https://github.com/fengyinchao/TaroCnode
-
預(yù)覽