【小程序】解决遍历过程中,类似排名前几个不同的样式处理

本文介绍使用小程序中的wx:for进行列表渲染,并结合wx:if、wx:elif、wx:else实现不同样式的动态展示。通过具体案例说明如何避免使用hidden属性以减少初始渲染消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小程序之wx:for(一)

初次开发小程序,能猜测到会遇到很多坑,所以在此记录,工作中开发小程序遇到的问题,以及如何解决问题的方法。也方便遇到类似问题的小伙伴思路。

话不多说,直接上图,上需求


这里写图片描述

需要达到这个效果,一开始遍历出来的结果是这样:
这里写图片描述

这里wx:for列表渲染就不说了,没有什么问题,正对于标题的问题后来就开始思考如何达到这个效果,想在后台数据中添加状态,感觉太麻烦(放弃)
于是想到wx:if wx:else,于是开始着手实验。
—wxss

.list-text{
  font-size: 14px;
  max-width: 200rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.first{
  background: #F34B36;
}
.second{
  background: #FF8E40;
}
.third{
  background: #FFC42D;
}

—wxml

<view class='page-hot'>
  <text class='page-h3'>热门搜索</text>
  <navigator class='hot-list' wx:for='{{list}}' url='{{item.url}}' open-type='navigate' wx:key='index'>
    <view class='list-id first' wx:if='{{index === 0}}'>{{item.id}}</view>
    <view class='list-id second' wx:elif='{{index === 1}}'>{{item.id}}</view>
    <view class='list-id third' wx:elif='{{index === 2}}'>{{item.id}}</view>
    <view class='list-id' wx:else >{{item.id}}</view>
    <text class='list-text'>{{item.text}}</text>
  </navigator>
</view>

最后的效果
这里写图片描述
通过wx:if wx:elif wx:else完美的解决了问题,利用列表渲染(wx:for)的index,在通过wx:if条件渲染来判断显示效果。这里之所以这里用wx:if来解决问题,没有用hidden 是应为hidden有更高的初始渲染消耗,而wx:if是更高的切换消耗。

第02个小程序遍历画笔(FlipThroughTheBrushes.cs) using System; using System.Reflection; using System.Windows; using System.Windows.Input; using System.Windows.Media; namespace Chapter02 { public class FlipThroughTheBrushes : Window { int index = 0; //索引值 PropertyInfo[] props; //属性数组 [STAThread] public static void Main() { Application app = new Application(); app.Run(new FlipThroughTheBrushes()); } public FlipThroughTheBrushes() { //取得Brushes类的成员,放在props中 props = typeof(Brushes).GetProperties(BindingFlags.Public | BindingFlags.Static); SetTitleAndBackground(); } //鼠标按下时 protected override void OnKeyDown(KeyEventArgs args) { if (args.Key == Key.Down || args.Key == Key.Up) { //Key.Down时index-1,Key.UP时index+1 index += args.Key == Key.Up ? 1 : props.Length - 1; //index对属性数组长度取余,防止索引越界 index %= props.Length; SetTitleAndBackground(); } base.OnKeyDown(args); } //设置背景 void SetTitleAndBackground() { Title = "Flip Through the Brushes - " + props[index].Name; Background = (Brush)props[index].GetValue(null, null); //设置背景画笔 } } } GetProperties()函数用于返回对象数组,参数是限制Brushes公开和静态的属性。其实这里可以不需要这样的限制,因为Brushes的属性本来全部都是public和static。 props[index].Name返回第index个属性的名称;props[index].GetValue(null, null)返回实际的SolidColorBrush对象,第一个参数是属性所在的对象,因为Brushes是一个静态属性,没有对应的对象,传入null;第二个参数只有在属性是索引器是才有必要。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值