鸿蒙学习记录

创建了一个名为 MyButton 的自定义组件,它显示了按钮的点击次数,并在每次点击时增加计数。

@Component struct MyButton { @State count: number = 1 build() { Row() { Text('点击次数:' + this.count.toString()) Button('点击我').onClick(() => { this.count++ }) } .justifyContent(FlexAlign.SpaceBetween) .padding(10) .border({ width: 1 }) .width('100%') } } @Entry @Component struct Index { build() { Column() { MyButton() MyButton({ count: 10 }) MyButton() } .padding(20) } }

传递参数

@Component struct MyFoodComponent { @State food: string = 'AAAA' dog: string = 'BBBB' // 普通变量也是响应式的 sayHello = () => { console.log('默认的打招呼') } build() { Row() { Text(`自定义组件 {this.dog} 喜欢吃 {this.food}`) Button('点击按钮') .onClick(() => { this.food += '!' this.dog += '.' this.sayHello() }) } .border({ width: 1 }) .padding(20) } } @Entry @Component struct Index { build() { Column() { MyFoodComponent() MyFoodComponent({ dog: 'CC', food: 'DD', sayHello() { console.log('外部传入的打招呼的逻辑') } }) .border({ width: 1 }) .padding(20) MyFoodComponent() } .padding(20) } }

事件处理和回调

@Component struct CardComponent { title: string = '' subTitle: string = '' clickHandler = () => { AlertDialog.show({ message: '默认的功能' }) } build() { Column() { Row() { Text(this.title).layoutWeight(1) Row() { Text(this.subTitle) Image($r('app.media.ic_public_arrow_right')) .width(20) } .onClick(() => { this.clickHandler() }) } Row() { Text('默认的内容') } .height(100) } .backgroundColor(Color.Pink) .borderRadius(10) .padding(10) .margin({ bottom: 20 }) } } @Entry @Component struct Index { build() { Column() { CardComponent({ title: '所有评论', subTitle: '查看更多', clickHandler() { AlertDialog.show({ message: '查看更多评论' }) } }) CardComponent({ title: '所有商品(100+)', subTitle: '查看更多', clickHandler() { AlertDialog.show({ message: '查看更多商品' }) } }) } .padding(20) } }

相关推荐
Selicens1 分钟前
git批量删除本地多余分支
前端·git·后端
wuhen_n6 分钟前
KeepAlive:组件缓存实现深度解析
前端·javascript·vue.js
前端付豪7 分钟前
Nest 项目小实践之图书展示和搜索
前端·node.js·nestjs
wuhen_n8 分钟前
Vue Router与响应式系统的集成
前端·javascript·vue.js
FansUnion35 分钟前
用 AI 自动生成壁纸标题、描述和 SEO Slug
javascript
青青家的小灰灰39 分钟前
金三银四面试官最想听的 React 答案:虚拟 DOM、Hooks 陷阱与大型列表优化
前端·react.js·面试
HelloReader39 分钟前
深入理解 Tauri 架构与应用体积优化实战指南
前端
lemon_yyds40 分钟前
vue 2 升级vue3 : ref 和 v-model 命名为同名
前端·vue.js
codingWhat40 分钟前
小程序里「嵌」H5:一套完整可落地的 WebView 集成方案
前端·uni-app·webview
重庆穿山甲44 分钟前
Java开发者的大模型入门:Spring AI Alibaba组件全攻略(二)
前端·后端