HarmonyOS NEXT 实战系列05-案例回关粉丝

需求:

提取 FansItemComp 组件进行复用,使用 @Prop 接收数据保证组件UI可动态渲染

封装 getFansAndFollowCount 方法获取互关人数且渲染

传入 onChange 方法,当子组件状态发送变更通知父组件进行列表数据更新

代码:

interface FansItem {

avatar: Resource

name: string

title: string

isFollow: boolean

}

@Entry

@Component

struct TestPage {

@State fansList: FansItem[] = [

{

name: '华为终端',

avatar: $r('app.media.flower'),

title: '2024,二百万粉阿华继续冲压!!!',

isFollow: false

},

{

name: '黑马程序员',

avatar: $r('app.media.flower'),

title: '领取课程源码+资料,关注黑马程序员公众,回复:领取资源02',

isFollow: true

},

{

name: '央视新闻',

avatar: $r('app.media.flower'),

title: '中央广播电视总台央视新闻官方账号',

isFollow: false

},

]

getFansAndFollowCount() {

return this.fansList.filter(item => item.isFollow)

.length

}

build() {

List() {

ListItem() {

Text(`互关 ${this.getFansAndFollowCount()} 人`)

.height(40)

}

ForEach(this.fansList, (item: FansItem, i) => {

ListItem() {

FansItemComp({

item,

onChange: (newItem) => {

this.fansList.splice(i, 1 , newItem)

}

})

}

}, (item: FansItem) => item.name)

}

.padding(15)

.width('100%')

.height('100%')

.margin({ top: 50 })

}

}

@Component

struct FansItemComp {

@Prop @Require item: FansItem

onChange: (item: FansItem) => void = () => {}

build() {

Row({ space: 15 }) {

Image($r('app.media.flower'))

.width(48)

.aspectRatio(1)

.borderRadius(24)

Column() {

Text(this.item.name)

Text(this.item.title)

.fontColor('#999999')

.maxLines(1)

.textOverflow({ overflow: TextOverflow.Ellipsis })

}

.layoutWeight(1)

.alignItems(HorizontalAlign.Start)

if (this.item.isFollow) {

Button('已关注')

.customButton()

.backgroundColor('#acacac')

.onClick(() => {

this.item.isFollow = false

this.onChange(this.item)

})

} else {

Button('回关')

.customButton()

.backgroundColor('#ffaa00')

.onClick(() => {

this.item.isFollow = true

this.onChange(this.item)

})

}

}

.width('100%')

.height(80)

}

}

@Extend(Button)

function customButton() {

.fontSize(12)

.padding(0)

.size({ width: 60, height: 30 })

}

注意:

${变量名} 字符串模版语法

子组件也可以接收函数

ForEach 第3个参数是唯一标识(默认是对象转成字符串),保证标识不变该 Item 不重新渲染

————————————————

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/zsgzsgzsgzsgzsg/article/details/146184981

全部评论

相关推荐

点赞 评论 收藏
分享
下个早班:秒挂就是不缺人
点赞 评论 收藏
分享
07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务