02-Taro頁面編寫和傳值

上回說到Taro打造hello-world應用。廢話不多說,直接上肉菜

State局部狀態(tài)

export default class Index extends Component {
  config = {
    navigationBarTitleText: '首頁'
  }
  state = {
    name: "hello 前端騷年"
  }
  render () {
    const { name } = this.state
    return (
      <View className='index'>
        <Text>{name}</Text>
      </View>
    )
  }
}

組件編寫和傳值

mkdir -p src/components/child
cd src/components/child
touch index.jsx

編寫組件,代碼如下

import Taro, { Component } from '@tarojs/taro'
import PropTypes from 'prop-types'
import { View, Text } from '@tarojs/components'
export default class Child extends Component {
  propTypes = {
    childName: PropTypes.string
  }
  defaultProps = {
    childName: ''
  }
  render () {
    const { childName } = this.props
    return (
      <View>
        <Text>我是肉菜中的{childName}</Text>
      </View>
    )
  }
}

在主頁面index中引入

import Child from "../../components/child";

render方法中即可運用

render () {
  const { name } = this.state
  return (
    <View className='index'>
      <Text>{name}</Text>
      <Child childName="蒜末child"/>
    </View>
  )
}

頁面跳轉和傳參

cd taroDemo
taro create --name next  // 創(chuàng)建next頁面

在 /src/app.jsx 中配置路由

pages: [
  'pages/index/index',
  'pages/next/next'
]

在主頁面Button上綁定跳轉事件

goNext() {
  Taro.navigateTo({url:'/pages/next/next?nextTheme=大保健'})
}

在next頁面接收參數(shù)

componentWillMount () {
  console.log(this.$router.params) // 輸出 {nextTheme: "大保健"}
  const { nextTheme } = this.$router.params
  this.setState({
    nextTheme
  })
}

其他頁面跳轉方式redirectTo、switchTab、navigateBack等和微信小程序很相似

請求遠程數(shù)據(jù)

const params = {
  url,
  data,
  header,
  method
}
const res = await Taro.request(params)

集成dva開發(fā)體驗更好,參考基于Taro + Dva構建的時裝衣櫥(電商實戰(zhàn)項目)

注意點

  1. 適配問題

    Taro以 750px 作為換算尺寸標準,尺寸單位使用px,默認會進行轉換rpx/rem。如果你希望部分 px 單位不被轉換成 rpx 或者 rem ,將px寫成Px或PX

  2. 盡量避免在 componentDidMount 中調用 this.setState,可在 WillMount 中處理

    你問為啥??因為在 componentDidMount 中調用 this.setState 會導致觸發(fā)更新

  3. 不要在調用 this.setState 時使用 this.state,會導致一些錯誤

  4. 多端組件

    假如有一個 Child 組件存在微信小程序、百度小程序和 H5 三個不同版本

    可在components目錄下分別創(chuàng)建child.js child.weapp.js child.h5.js

    // 引用不變,編譯會自動識別
    import Child from '../../components/child'
    

taroDemo 項目地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容