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注解。

相关推荐
Georgewu1 小时前
【HarmonyOS 5】鸿蒙中自定义弹框OpenCustomDialog、CustomDialog与DialogHub的区别详解
harmonyos
塞尔维亚大汉1 小时前
鸿蒙内核源码分析(消息封装篇) | 剖析LiteIpc 进程通讯内容
harmonyos·源码阅读
Georgewu1 小时前
【HarmonyOS NEXT】鸿蒙跳转华为应用市场目标APP下载页
harmonyos
ajassi20003 小时前
开源 Arkts 鸿蒙应用 开发(六)数据持久--文件和首选项存储
linux·开源·harmonyos
塞尔维亚大汉4 小时前
鸿蒙内核源码分析(共享内存) | 进程间最快通讯方式
harmonyos·源码阅读
生如夏花℡8 小时前
HarmonyOS学习记录4
学习·华为·harmonyos
xq95278 小时前
编程之路2025年中总结,勇往直前 再战江湖
harmonyos
枫叶丹49 小时前
【HarmonyOS Next之旅】DevEco Studio使用指南(四十二) -> 动态修改编译配置
华为·harmonyos·deveco studio·harmonyos next
前端世界20 小时前
鸿蒙UI开发全解:JS与Java双引擎实战指南
javascript·ui·harmonyos
阿巴~阿巴~1 天前
操作系统核心技术剖析:从Android驱动模型到鸿蒙微内核的国产化实践
android·华为·harmonyos