使用前面学习的相关组件和api实现联系人的CRUD; 效果如下

父组件
import { Contacts } from '../domain/Model'
import ContactsItem from '../components/ContactsItem'
@Entry
@Component
struct ContactsExample {
@State contactsArr: Contacts[] = [
new Contacts(1, '张三丰', false, false, '18898789098', false),
new Contacts(2, '张无忌', false, false, '15876768989', false)
]
@State isShow: boolean = false
@State next: number = 1000
build() {
Column() {
Row() {
Text('联系人').fontSize(20)
Blank()
Button(this.isShow ? '取消' : '选择').onClick(() => {
this.isShow = !this.isShow
})
Button('+').margin({ left: 10 }).onClick(() => {
this.contactsArr.push(new Contacts(this.next++, Math.random().toFixed(3)
.toString(), false, false, `1899898${this.next}`, false))
})
}.width('100%')
List({ space: 5 }) {
ForEach(this.contactsArr, (contacts: Contacts, index: number) => {
ListItem() {
ContactsItem({ contacts: contacts, isShow: $isShow })
}
}, (contacts: Contacts) => contacts.id.toString())
}.margin({ top: 20 }).layoutWeight(1)
if (this.isShow) {
Button('删除')
.backgroundColor(Color.Red)
.type(ButtonType.Normal)
.onClick(() => {
this.contactsArr = this.contactsArr.filter(item => !item.isSelect)
})
}
}.width('100%')
.padding(20)
}
}
子组件
import { Contacts } from '../domain/Model'
@Component
export default struct ContactsItem {
@ObjectLink contacts: Contacts
@Link isShow: boolean
build() {
Column() {
Row({ space: 5 }) {
if (this.isShow) {
Checkbox().select(this.contacts.isSelect).onChange((val) => {
console.log(val + "")
this.contacts.isSelect = val
})
}
Image($rawfile('avatar.jpg')).width(30).height(30)
Text(this.contacts.name)
Blank()
Image($rawfile(this.contacts.isSave ? 'collection.png' : 'cancel_collection.png'))
.width(30)
.height(30)
.onClick(() => {
console.log(this.contacts.isSave + "")
this.contacts.isSave = !this.contacts.isSave
})
}.width('100%')
.onClick(() => {
this.contacts.isExpand = !this.contacts.isExpand
})
Divider().strokeWidth(3).margin({ top: 5 })
if (this.contacts.isExpand) {
Row() {
Text('联系人:')
Text(this.contacts.phone)
}.width('100%')
}
}.width('100%')
.margin({ top: 10 })
}
}
模型(class类)
@Observed
export class Contacts {
id: number
name: string
isSelect: boolean
isSave: boolean
phone: string
isExpand: boolean
constructor(id: number, name: string, isSelect: boolean, isSave: boolean, phone: string, isExpand: boolean) {
this.id = id
this.name = name
this.isSelect = isSelect
this.isSave = isSave
this.phone = phone
this.isExpand = isExpand
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2023-04-12 CompletableFuture入门