小程序 手写picker
时间: 2023-09-20 17:13:50 浏览: 59
手写 Picker 组件的实现主要涉及以下几个方面:
1. 点击触发 Picker 弹出;
2. Picker 内容展示;
3. Picker 内容滚动;
4. 选中项高亮和回调。
具体实现可以参考以下代码:
```
// Wxss 样式
.picker {
display: none;
position: fixed;
left: 0;
bottom: 0;
width: 100%;
height: 300rpx;
background-color: #fafafa;
z-index: 9999;
}
.picker-header {
display: flex;
justify-content: space-between;
align-items: center;
height: 80rpx;
font-size: 32rpx;
padding: 0 32rpx;
background-color: #f5f5f5;
}
.picker-cancel {
color: #999;
}
.picker-confirm {
color: #007aff;
}
.picker-content {
display: flex;
justify-content: center;
align-items: center;
height: 220rpx;
overflow: hidden;
}
.picker-list {
flex: 1;
height: 100%;
overflow: hidden;
}
.picker-item {
height: 80rpx;
line-height: 80rpx;
text-align: center;
font-size: 28rpx;
color: #333;
}
.picker-item-active {
color: #007aff;
}
// Wxml 模板
<view class="picker" style="{{showPicker ? 'display:flex;' : ''}}">
<view class="picker-header">
<view class="picker-cancel" bindtap="cancelPicker">取消</view>
<view>{{title}}</view>
<view class="picker-confirm" bindtap="confirmPicker">确定</view>
</view>
<view class="picker-content">
<view class="picker-list" style="transform: translateY({{translateY}}rpx);">
<block wx:for="{{list}}" wx:key="index">
<view class="picker-item {{index === activeIndex ? 'picker-item-active' : ''}}" data-index="{{index}}" bindtap="selectItem">{{item}}</view>
</block>
</view>
</view>
</view>
// Js 代码
Page({
data: {
showPicker: false,
title: '',
list: [],
activeIndex: 0,
translateY: 0,
},
// 点击触发 Picker
showPicker() {
this.setData({
showPicker: true,
})
},
// Picker 取消
cancelPicker() {
this.setData({
showPicker: false,
})
},
// Picker 确定
confirmPicker() {
const { activeIndex, list } = this.data
const selectedValue = list[activeIndex]
// 触发回调
this.triggerEvent('select', selectedValue)
this.setData({
showPicker: false,
})
},
// 选择项
selectItem(e) {
const { index } = e.currentTarget.dataset
const { list, activeIndex } = this.data
const len = list.length
const distance = index - activeIndex
const translateY = distance * 80
let newIndex = activeIndex + distance
// 处理边界情况
if (newIndex < 0) {
newIndex = len - 1
} else if (newIndex >= len) {
newIndex = 0
}
this.setData({
activeIndex: newIndex,
translateY,
})
},
})
```
上述代码实现了一个简单的 Picker 组件,具体效果可以自行调整样式。需要注意的是,手写 Picker 组件相对于原生的 Picker 组件需要自行处理滚动、边界等问题,但是也更加灵活,可以实现更多定制化的需求。
阅读全文