Harmony AttributeModifier 基本使用

csharp 复制代码
declare interface AttributeModifier<T> {

    /**
     * Defines the normal update attribute function.
     */
    applyNormalAttribute?(instance: T): void;
    /**
     * Defines the pressed update attribute function.
     */
    applyPressedAttribute?(instance: T): void;
    /**
     * Defines the focused update attribute function.
     */
    applyFocusedAttribute?(instance: T): void;
    /**
     * Defines the disabled update attribute function.
     */
    applyDisabledAttribute?(instance: T): void;
    /**
     * Defines the selected update attribute function.
     */
    applySelectedAttribute?(instance: T): void;
}

AttributeModifier 定义的方法会在组件切换到对应的状态的时候出发点。

基本用法:1 实现AttributeModifier 类型T的指定决定于这个Modifier最终作用在哪个组件上。通过对应组件的 attributeModifier 方法的参数就可以知道具体的类型。

scss 复制代码
class ButtonModifierImpl implements  AttributeModifier<ButtonModifier> {
  isClick = false;
  applyPressedAttribute(instance: ButtonModifier): void {
    if(this.isClick){
      instance.backgroundColor(Color.Red)
    }else {
      instance.backgroundColor(Color.Blue)
    }
  }

  applyNormalAttribute(instance: ButtonModifier): void {
    if(this.isClick){
      instance.backgroundColor(Color.Red)
    }else {
      instance.backgroundColor(Color.Blue)
    }
  }
}

2 使用 我这里是作用在Button上,所以T的类型就是ButtonModifier

less 复制代码
@State
buttonModifier : ButtonModifierImpl =  new ButtonModifierImpl();
kotlin 复制代码
Column(){
  Button("测试Modifier")
    .attributeModifier(this.buttonModifier)
  Button("测试Modifier")
    .backgroundColor(Color.Blue)
    .onClick((event)=>{
     this.buttonModifier.isClick = !this.buttonModifier.isClick
    })
}

2.1 当Button 触发不同的回调的时候,就会设置新的样式。比如点击的时候。 2.2 也可以在Modifier中定义变量。当变量发生改变的时候,也会触发回调。注意的是buttonModifier必须使用@State注解。

相关推荐
爱笑的眼睛1143 分钟前
HarmonyOS 应用开发:深入探索截屏与录屏API的创新实践
华为·harmonyos
爱笑的眼睛111 小时前
深入探讨HarmonyOS中ListItem的滑动操作实现与优化
华为·harmonyos
爱笑的眼睛115 小时前
可可图片编辑 HarmonyOS 上架应用分享
华为·harmonyos
东林知识库5 小时前
HarmonyOS 6 开发者预览版 Beta 招募
华为·harmonyos
无尽星海max5 小时前
用虚拟机体验纯血鸿蒙所有机型!
华为·harmonyos
I'mAlex5 小时前
0 基础入门鸿蒙:跟着《HarmonyOS 第一课》1 周掌握应用开发核心能力
华为·harmonyos
工藤学编程5 小时前
仓颉原子操作封装:从底层原理到鸿蒙高并发实战
华为·harmonyos
User_芊芊君子5 小时前
【成长纪实】我的鸿蒙成长之路:从“小白”到独立开发,带你走进鸿蒙的世界
学习·华为·harmonyos·鸿蒙开发
●VON5 小时前
【成长纪实】三个月的鸿蒙成长之路:大学生从0开始的鸿蒙心得与体会
华为·架构·harmonyos·鸿蒙·鸿蒙系统·鸿蒙开发·成长纪实
Jinkxs5 小时前
仓颉语言性能优化指南:实测对比,让鸿蒙应用运行效率提升 40%
华为·性能优化·harmonyos