写在前:想自己写一个开关switch 如下图;并写成组件
首先,根据小程序文档提供的 自定义组件;可以新建一个文件夹 包括: json wxss wxml js 四个文件夹;
小程序右键,新建Component 之后,此文件夹json中已经设置:"component": true, js文件夹也是已经初始化好了。
其次,可以先引用这个组件,然后看效果;
在我们需要用到的页面json 中,我的是index.json文件
{
"navigationBarTitleText": "引入自定义组件",
"usingComponents": {
"switch-button": "../../comment/switch/switch"
}
}
注:switch-button 是 引用组件的正确路径
然后,在index.wxml 中使用组件
样式:
.radio-box {
width: 50px;
height: 100%;
margin-right: 28rpx;
justify-content: center;
align-items: center;
}
最后,自定义组件,我的是在comment下建switch文件夹,所以
switch.wxml :
switch.wxss:
/* pages/comment/switch/switch.wxss */
.radio-box {
width: 50px;
height: 100%;
margin-right: 28rpx;
justify-content: center;
align-items: center;
}
.row {
display: flex;
flex-direction: row;
}
.radio {
width: 45px;
height: 22px;
background-color: #e0e4ed;
border-radius: 12px;
border: 1px solid #f5f5f5;
padding-left: 1px;
padding-right: 1px;
align-items: center;
}
.circle {
width: 18px;
height: 18px;
background-color: #fff;
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
}
.centerline {
width: 2px;
height: 16rpx;
background-color: #e0e4ed;
}
.centercir {
width: 5px;
height: 5px;
border: 1px solid #e0e4ed;
border-radius: 50%;
background-color: #fff;
}
switch.js:
// pages/comment/switch/switch.js
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 样式隔离
*/
options: {
styleIsolation: 'isolated'
},
/**
* 组件的初始数据
*/
data: {
swit: false,
},
/**
* 组件的方法列表
*/
methods: {
// 单选按钮
switchTap: function() {
let swit = this.data.swit
// 点击按钮后
const animation = wx.createAnimation({
duration: 500,
timingFunction: 'ease',
})
const anim = wx.createAnimation({
duration: 500,
timingFunction: 'ease',
})
this.animation = animation
this.animation = anim
if (swit) {
animation.translateX(0).step()
anim.backgroundColor('#e0e4ed').step()
this.setData({
move: animation.export(),
movebg: anim,
swit: !swit
})
} else {
animation.translateX(27).step()
anim.backgroundColor('#fe6969').step()
this.setData({
move: animation.export(),
movebg: anim,
swit: !swit
})
}
},
}
})
注:组件间的传值,待续。。。