1、安裝腳手架
cnpm install -g @tarojs/cli
2、初始化項(xiàng)目
taro init myProject
初學(xué)者建議:ts:no,css預(yù)處理器:less,選擇模版:默認(rèn)模版
3、安裝依賴
cnpm install
cnpm install typescript --save(自定義安裝ts時(shí)用到)
4、各端啟動(dòng)項(xiàng)目
WEB端——npm run dev:h5
微信小程序——npm run dev:weapp
支付寶小程序——npm run dev:alipay
百度小程序——npm run dev:swan
ReactNative——npm run dev:rn
5、生命周期&State
componentWillMount () {
console.log('第一次渲染之前執(zhí)行,只執(zhí)行一次')
}
componentDidMount () {
console.log('第一次渲染之后執(zhí)行,只執(zhí)行一次')
this.setState({
name: 'hello china!',
text: '李四',
obj: {key: [{name: "張三"}]}
},()=>{
console.log(this.state.name)
})
console.log(this.state.name)
}
componentWillUpdate(){
console.log('state數(shù)據(jù)將要更新')
}
componentDidUpdate(){
console.log('state數(shù)據(jù)更新之后')
}
componentWillReceiveProps(nextProps){
//會(huì)在父組件傳遞給子組件的參數(shù)發(fā)生改變時(shí)觸發(fā)
}
shouldComponentUpdate(nextProps,nextState){
//檢查此次setState是否要進(jìn)行render調(diào)用
//一般用來多次的setState調(diào)用時(shí) 提升render的性能
if(nextState.text == '李四'){
return true;
} else{
return false;
}
}
componentWillUnmount () {
console.log('卸載時(shí)執(zhí)行,只執(zhí)行一次')
}
componentDidShow () {
//reactjs 是不存在的,taro中存在
//頁面顯示時(shí)觸發(fā)
}
componentDidHide () {
//reactjs 是不存在的,taro中存在
//頁面隱藏時(shí)觸發(fā)
}
狀態(tài)更新是異步的,可通過在setState中加回調(diào)函數(shù)獲取更新后的值,
更新數(shù)據(jù)不像vue中直接this.state.name,而是通過
this.setState({
name: 'hello world!',
text: 'wayne'
},()=>{
console.log(this.state.name)
})
6、父子組件傳遞函數(shù)事件時(shí)區(qū)別
h5中組件事件調(diào)用沒有限制,但在小程序中必須以on開頭,為了兼容多端支持,需要按照taro規(guī)范書寫
//parent.js
test() {
console.log('test父組件傳遞參數(shù)給子組件')
}
render () {
let {name,obj} = this.state
return (
<View className='index'>
<Text>{this.state.name}</Text>
<Text>{this.state.text}</Text>
<Child name={name} obj={obj} ontest={this.test}></Child>
</View>
)
}
//child.js
cl () {
this.props.ontest();
}
render(){
let {name,obj} = this.props
return (
<View onClick={this.cl.bind(this)}>
<Text>我是child子節(jié)點(diǎn){name + '---' + obj.key[0].name}</Text>
</View>
)
}
}