taro框架是開發小程序的一種基於React語法的框架,是京東推出的。我之前在項目中使用過,現在記錄一下。
taro的項目目錄如下:
其中,src放的是源碼,config放的是部署配置文件。
src中有放置utils(公共函數等工具)、template(模板)、pages(頁面)、components(組件)、assets(圖片資源)的文件夾。
其中,app.js的作用相當於小程序原生的app.json,對全局進行配置。
app.js的示例代碼如下:
import Taro, { Component } from '@tarojs/taro' import '@tarojs/async-await' import Index from './pages/index' import './app.less' import 'taro-ui/dist/style/index.scss' // 如果需要在 h5 環境中開啟 React Devtools // 取消以下注釋: // if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5') { // require('nerv-devtools') // } class App extends Component { config = { pages: [ 'pages/index/index', 'pages/myInfo/myInfo', 'pages/queryScanCode/queryScanCode', 'pages/bindModel/bindModel', ], window: { backgroundTextStyle: 'dark', navigationBarBackgroundColor: '#fff', navigationBarTitleText: 'WeChat', navigationBarTextStyle: 'black' }, tabBar:{ color: '#626567', selectedColor: '#6e9eea', backgroundColor: '#FBFBFB', borderStyle: 'white', list:[{ pagePath: 'pages/queryScanCode/queryScanCode', text: '設備', iconPath: "assets/img/icon_query@2x.png", selectedIconPath: "assets/img/icon_query_sel@2x.png", }, { pagePath: 'pages/bindEquipment/bindEquipment', text: '綁定', iconPath: "assets/img/icon_bound@2x.png", selectedIconPath: "assets/img/icon_bound_sel@2x.png", }, { pagePath: 'pages/myInfo/myInfo', text: '我的', iconPath: "assets/img/icon_person@2x.png", selectedIconPath: "assets/img/icon_person_sel@2x.png" }] }, networkTimeout: { "request": 60000 }, } componentDidMount () {} componentDidShow () {} componentDidHide () {} componentDidCatchError () {} // 在 App 類中的 render() 函數沒有實際作用 // 請勿修改此函數 render () { return ( <Index /> ) } } Taro.render(<App />, document.getElementById('app'))
由以上代碼,我們可以看出:
1.taro的代碼風格跟React很像,如使用了React的組件生命周期函數、使用render進行渲染等。
2.該頁面渲染Index組件。在taro中所有的頁面和組件都可以看成是組件,但是頁面需要在全局配置時配置頁面路由以區別。
在pages文件夾中,含有各個頁面的文件夾,各個頁面的文件夾都含有一個js和less文件。
js負責邏輯和頁面的渲染,less負責樣式。
代碼示例1:template.js
import Taro, { Component } from '@tarojs/taro' import { View, Text, Image} from '@tarojs/components' import './template.less' class Template extends Component { constructor(){ super(...arguments) this.state = { } } render () { return ( <View className='template'> <Text>Template</Text> </View> ) } } export default Template
由以上代碼可得:
1.組件名需要首字母大寫。
2.React中的state相當於小程序原生的data。
3.taro主要是用<View>和<Text>來構建頁面。
代碼示例2:addCut.js
import Taro, { Component } from '@tarojs/taro' import { View, Text, Image} from '@tarojs/components' import './addCut.less' import { getEvent, getFoodCount, setFoodCount } from '../../utils/common' const event = getEvent() class AddCut extends Component { constructor(){ super(...arguments) this.state = { num:0 } } componentDidMount(){ let num = getFoodCount(this.props.food) this.setState({num:num}) //監聽 event.on('changeCat',()=>{ this.setState({num:getFoodCount(this.props.food)}) }) } add(){ setFoodCount(this.props.food,this.state.num,'add',()=>{ this.setState({num:getFoodCount(this.props.food)},()=>{ event.emit('addCut') event.emit('clickAgain') }) }) } sub(){ if(this.state.num > 0){ setFoodCount(this.props.food,this.state.num,'sub',()=>{ this.setState({num:getFoodCount(this.props.food)}) event.emit('addCut') event.emit('clickAgain') }) }else{ console.error('減少菜品出現異常') } } render () { let { num } = this.state return ( <View className='addCut'> {/* 兩種不同的綁定事件方式 */} <Text className={'op_img '+(num>0?'':'hide')} onClick={this.sub.bind(this)}>-</Text> <Text className={'num '+(num>0?'':'hide')}>{num}</Text> <Text className='op_img' onClick={(e)=>this.add(e)}>+</Text> </View> ) } } export default AddCut
由以上代碼可得:
1.可以通過import導入公共函數。
2.constructor可以初始化組件。
3.setState需要時間,之后的執行語句需要寫在回調函數中。
4.頁面上觸發函數調用時需要bind(this)或是使用(e)=>this.xxx(e)的語法。
代碼示例3:common.js
import Taro from '@tarojs/taro' import Event from './event' const key = 'meituan' //公共函數 export function getFoodCount(food){ //讀緩存 let store = Taro.getStorageSync(key) if(store&&store[food.id]){ return store[food.id].num }else{ return 0 } } export function setFoodCount(food,num,type,cb){ let store = Taro.getStorageSync(key) //給store賦空對象初值 if(!store) store = {} if(store&&store[food.id]){ if(type=='sub'){ if(num==1){ //從緩存中刪除數據結構 delete store[food.id] }else{ store[food.id].num = num - 1; } }else{ store[food.id].num = num + 1; } }else{ //合並屬性 store[food.id] = { num:1, ...food } } //設置緩存 Taro.setStorageSync(key,store) cb && cb() } export function getAllFoodInfo(){ let allNum = 0 let allPrice = 0 let store = Taro.getStorageSync(key) if(store){ //遍歷對象的key Object.keys(store).map((key)=>{ if(store[key]){ allPrice += store[key].price * store[key].num allNum += store[key].num } }) } return { allNum, allPrice } } const e = new Event() //必須為單例模式 export function getEvent(){ return e }
由以上代碼可得:
1.公共函數使用export進行導出。
2.小程序緩存用Taro.getStorageSync和Taro.setStorageSync來實現。
更多用法可以查看taro示例項目https://github.com/LuoYiHao/taroDemo。