歷史的發展,小程序風行一時,安卓/ios/H5/微信小程序/支付寶小程序/頭條小程序,產品經理讓你適配這麼多,你的心情如何呢?然而總會有人給我們造出合適的工具,解放生產力,一次編碼,多端運行。開始探索之旅吧!css
安裝 Taro 開發工具 @tarojs/cli
使用 npm 或者 yarn 全局安裝,或者直接使用npxnode
$ npm install -g @tarojs/cli
$ yarn global add @tarojs/cli
複製代碼
$ taro init multiportApp
複製代碼
按照本身狀況選擇安裝便可
進入對應目錄,執行命令啓動。ios
npm run dev:h5
複製代碼
會出現啓動成功的界面,以下git
自動就會打開瀏覽器,出現hello world界面,表示項目啓動成功了!在pages/index/index.js文件中添加以下github
constructor(props){
super(props);
this.state={
val:'',
todos:[
{
title:'吃飯',
done:false
},
{
title:'睡覺',
done:false
},
{
title:'coding',
done:false
}
]
}
}
複製代碼
render () {
return (
<View className='index'>
<Text>Hello world!</Text>
{
this.state.todos.map((item,index)=>{
return <View key={index}>{item.title}</View>
})
}
</View>
)
}
複製代碼
列表渲染搞定。 npm
引入組件小程序
import { View, Text,Input,Button } from '@tarojs/components'
複製代碼
render修改微信小程序
render () {
return (
<View className='index'>
<Text>Hello world!</Text>
<Input value={this.state.val} onInput={this.handleInput}></Input>
<Button onClick={this.handleClick}>添加</Button>
{
this.state.todos.map((item,index)=>{
return <View key={index}>{item.title}</View>
})
}
</View>
)
}
複製代碼
添加方法瀏覽器
handleInput=(e)=>{
this.setState({
val:e.detail.value
})
}
handleClick=()=>{
this.setState({
todos:[...this.state.todos,{title:this.state.val,done:false}],
val:''
})
}
複製代碼
一個簡單的todolist就算完成了,界面有點醜,繼續優化! bash
npm install --save taro-ui
複製代碼
因爲引用 node_modules
的模塊,默認不會編譯,因此須要額外給 H5 配置 esnextModules
,在 taro 項目的 config/index.js
中新增以下配置項:
h5: {
esnextModules: ['taro-ui']
}
複製代碼
在app.scss中引入
@import 'taro-ui/dist/style/index.scss'
複製代碼
在index.js中引入
import { AtList, AtListItem } from "taro-ui"
複製代碼
修改render
render () {
return (
<View className='index'>
<Text>Hello world!</Text>
<Input value={this.state.val} onInput={this.handleInput}></Input>
<Button onClick={this.handleClick}>添加</Button>
<AtList>
{
this.state.todos.map((item,index)=>{
return <AtListItem key={index} title={item.title}></AtListItem>
})
}
</AtList>
</View>
)
}
複製代碼
<AtListItem key={index} title={item.title} className={{'done':item.done}} isSwitch switchIsCheck={item.done} onSwitchChange={(e)=>this.handleChange(e,index)}></AtListItem>
複製代碼
增長一個isSwitch,switch切換事件,class。
增長事件
handleChange=(e,i)=>{
console.log(e,i);
const todos=[...this.state.todos];
todos[i].done=e.detail.value;
this.setState({
todos
})
}
複製代碼
在同級目錄下index.scss中增長樣式
.done{
color: red;
text-decoration: line-through;
}
複製代碼
h5效果
微信小程序中的效果 這就是這個框架的威力,感謝taro開發團隊。同步發表於我的博客
最後在說一句,正在找工做,座標北京,各位大佬有合適的機會推薦下哈!