Taro 框架整理(精简)

2,166 阅读2分钟

启动

npm run dev:weapp
taro build --type weapp --watch

样式相关

  • 使用 flex 布局,主轴方向默认 column
  • 使用 className / style 添加样式
  • app.js 引入的就是全局样式
  • background 等价于 background-color
  • background-image 特性使用 <Image /> 标签配合 flex 布局实现
  • 组件样式隔离
    • 外部样式类 externalClasses
    • 全局样式类 options.addGlobalClass

命名规范

  • 普通文件命名 util.js util_helper.js
  • 组件文件命名 ReservationCard.jsx
  • 变量名 const myVar = 'hello'
  • 类名要以大写字母开头 class Animal {}
  • 属性名 <Foo userName='hello' phoneNumber={12345678}/>

书写顺序

  1. static 静态方法
  2. constructor
  3. componentWillMount
  4. componentDidMount
  5. componentWillReceiveProps
  6. shouldComponentUpdate
  7. componentWillUpdate
  8. componentDidUpdate
  9. componentWillUnmount
  10. 点击回调或者事件回调 比如 onClickSubmit() 或者 onChangeDescription()
  11. render

JSX 书写规范

  • 不要以 class/id/style 作为自定义组件的属性名
  • 不要使用 HTML 标签
  • 不要使用 undefined 来初始化变量
  • map 循环时请给元素加上 key 属性
  • 尽量避免在 componentDidMount 中调用 this.setState
  • 不要在 componentWillUpdate/componentDidUpdate/render 中调用 this.setState
  • 组件最好定义 defaultProps
  • 值为 true 的属性可以省略书写值
  • 事件绑定均以 on 开头
  • 子组件传入函数时属性名需要以 on 开头
  • 必须声明 Taro

生命周期

官方文档 - 框架
官方文档 - 组件生命周期

生命周期 入口文件 页面 组件
componentWillMount() X X X
componentDidMount() X X X
componentDidShow() X X
componentDidHide() X X
componentWillReceiveProps(nextProps) X
shouldComponentUpdate(nextProps, nextState) X X
componentWillUpdate(nextProps, nextState) X X
componentDidUpdate(prevProps, prevState) X X
componentWillUnmount() X X
componentDidCatchError(String error) X
componentDidCatchError(Object) X

页面事件处理函数

  • onPullDownRefresh()
  • onReachBottom()
  • onPageScroll(Object)
  • onShareAppMessage(Object)
  • onResize(object)
  • onTabItemTap(Object)
  • componentWillPreload()

配置

路由

Taro.navigateTo({ url: '/pages/page/path/name' })
Taro.redirectTo({ url: '/pages/page/path/name' })

路由传参

方式一:

  • 添加参数
Taro.navigateTo({ url: '/pages/page/path/name?id=2&type=test' })
  • 获取参数
this.$router.params

方式二(小程序中):

  • 添加参数
this.$preload('key', 'val')
Taro.navigateTo({ url: '/pages/B/B' })
  • 获取参数
this.$router.preload

官方文档 - 导航 API

语法特性

条件渲染

  • 使用变量来储存元素 let st = <Text>XXX</Text>
  • 逻辑运算符 &&
  • 条件表达式 ?:
  • 枚举条件 {..}[status]

列表渲染

  • map + key

插槽

  • 默认插槽 this.props.children
  • 具名插槽 this.props.renderXyyy (组合都必须用 render 开头)
  • 作用域插槽 this.props.renderXyz(this.state)

函数式组件

  • 普通函数式组件(纯函数)
  • 类函数式组件(在在类组件内部)
  • 闭包函数式组件(在普通函数式组件内部)

引用 Ref

  • xxRef = (node) => this.xx = node <Comp ref={this.xxRef} />
  • this.xx = Taro.createRef() <Comp ref={this.xx} />
  • const xx = useRef(null) <Comp ref={xx} />

数据传输

  • props 父子间通信
  • Context 发布订阅模式
    • Taro.createContext
    • Context.Provider
    • Class.contextType / useContext
  • events 消息机制
    • Taro.eventCenter.on
    • Taro.eventCenter.trigger
    • Taro.eventCenter.off
  • storage 数据缓存
    • Taro.setStorage
    • Taro.getStorage
    • Taro.removeStorage
    • Taro.clearStorage

Hooks

官方文档 - Hooks API
React - Hooks API Reference

useState

useReducer 替代

const [state, setState] = useState(initialState)
const [state, setState] = useState(() => {
    const initialState = someExpensiveComputation(props)
    return initialState
})

useEffect

useEffect(() => {
    let num = 0
    let timeId = setInterval(() => {
        console.log(num++)
    }, 1e3)
    return () => {
        clearInterval(timeId)
    }
}, [])

useReducer

function init(initialCount) {
    return { count: initialCount }
}
function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return { count: state.count + 1 }
        case 'decrement':
            return { count: state.count - 1 }
        case 'reset':
            return init(action.payload)
        default:
            throw new Error()
    }
}
export default function Counter({ initialCount }) {
    const [state, dispatch] = useReducer(reducer, initialCount, init)
    return (
        <View>
            Count: {state.count}
            <Button
                onClick={() =>
                    dispatch({ type: 'reset', payload: initialCount })
                }
            >
                Reset
            </Button>
            <Button onClick={() => dispatch({ type: 'increment' })}>+1</Button>
            <Button onClick={() => dispatch({ type: 'decrement' })}>-1</Button>
        </View>
    )
}

useCallback

const memoizedCallback = useCallback(() => {
    doSomething(a, b)
}, [a, b])

useContext

const value = useContext(MyContext)

useMemo

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b])

useRef

const refContainer = useRef(initialValue)

其他

  • 使用 this.$componentType 来判断当前 Taro.Component 是页面还是组件
    • 取值 PAGECOMPONENT
  • 内置环境变量 process.env.TARO_ENV
    • 取值 weapp / h5 / swan / alipay / rn / tt / qq / quickapp
  • 多端组件文件
    • test.js / test.weapp.js / test.h5.js / test.swan.js / test.qq.js / test.quickapp.js
    • 多端文件对外的接口要保持一致
  • 环境判断 Taro.ENV_TYPE / Taro.getEnv()
    • ENV_TYPE.WEAPP - 微信小程序环境
    • ENV_TYPE.SWAN - 百度小程序环境
    • ENV_TYPE.ALIPAY - 支付宝小程序环境
    • ENV_TYPE.TT - 字节跳动小程序环境
    • ENV_TYPE.WEB - WEB(H5)环境
    • ENV_TYPE.RN - ReactNative 环境
  • 消息机制 Taro.Events / Taro.eventCenter
    • events.on('eventName', handler)
    • events.trigger('eventName', ...arg)
    • events.off('eventName', [handler])
    • events.once('eventName', handler)
    • events.off()

参考