上回說到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)項目)
注意點
-
適配問題
Taro以
750px作為換算尺寸標準,尺寸單位使用px,默認會進行轉換rpx/rem。如果你希望部分px單位不被轉換成rpx或者rem,將px寫成Px或PX -
盡量避免在 componentDidMount 中調用 this.setState,可在 WillMount 中處理
你問為啥??因為在
componentDidMount中調用this.setState會導致觸發(fā)更新 不要在調用 this.setState 時使用 this.state,會導致一些錯誤
-
多端組件
假如有一個
Child組件存在微信小程序、百度小程序和 H5 三個不同版本可在components目錄下分別創(chuàng)建child.js child.weapp.js child.h5.js
// 引用不變,編譯會自動識別 import Child from '../../components/child'