如何在微信小程序自定义个性化radio组件

微信小程序的radio组件是标准化的,做出来的视觉效果千篇一律。笔者尝试做了一个自定义的radio组件,效果很好,与大家分享一下。废话不多说,上干货:
1、WXML模板:


<template name="zradio">
<view class="radiobox" data-index="{{index}}" bindtap="radioChange">
   <view wx:if="{{zradio[index].status}}" class="checked}}">·view>
   <view wx:else class="unchecked}}">view>
   <view wx:if="{{zradio[index].status}}" style="color:red;">{{zradio[index].name}}view>
   <view wx:else style="color:#000000;">{{zradio[index].name}}view>
 view>
template>

2、WXML:


<import src="/pages/common/lib/common.wxml" />
<view class="container">
  <template is="zradio" data="{{index: 0, zradio: zradio }}"/>
  <template is="zradio" data="{{index: 1, zradio: zradio }}"/>
  <template is="zradio" data="{{index: 2, zradio: zradio }}"/>
view>

3、WXSS:

/* pages/radio/radio.wxss */
.container{
  height: 300rpx;
  width:300rpx;
  display:flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: flex-start;
  margin-top:200rpx;  
  margin-left:100rpx; 
  border: 1rpx solid red; 
}
.radiobox{
  display:flex;
  flex-direction: row;
  align-items: center;
}
.checked {
  display:flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height:30rpx;
  width:30rpx;
  border-radius: 50%;
  color:red;
  border:1rpx solid red;
}
.unchecked {
  height:30rpx;
  width:30rpx;
  border-radius: 50%;
  color:black;
  border:1rpx solid black;
}

4、JS:

//pages/radio/radio.js
Page({
  data: {
    zradio: [
      { name: '中国', status: false },
      { name: '美国', status: false },
      { name: '英国', status: false }
    ]
  },
  radioChange: function (e) {
    var zradio = this.data.zradio;
    var index = e.currentTarget.dataset.index;
    console.log(e);
    if (this.data.zradio[index].status) {
      zradio[index].status = false;
    } else {
      zradio[index].status = true;
    };
    this.setData({
      zradio: zradio
    })
  }
})

**后记:
如果大家想做出自己的风格,只需要修改WXSS文件即可。**

你可能感兴趣的:(微信)