zoukankan      html  css  js  c++  java
  • 使用taro框架开发小程序

    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

  • 相关阅读:
    关于ActionBar的向下兼容
    hdu 4869 Task(馋)
    javascritpt 原型链
    PKU 1276 Cash Machine
    前端开发——图片标注工具
    Android Notification通知详细解释
    android 如何加入第一3正方形lib图书馆kernel于
    linux 在系统启动过程
    android CountDownTimer 倒计时
    承受
  • 原文地址:https://www.cnblogs.com/luoyihao/p/12390753.html
Copyright © 2011-2022 走看看