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

相关推荐
lqj_本人3 小时前
鸿蒙Cordova开发踩坑记录:跨域请求的“隐形墙“
harmonyos
Z***25807 小时前
HarmonyOS在物联网场景的应用
物联网·华为·harmonyos
Pocker_Spades_A9 小时前
John the Ripper 在 HarmonyOS 上的构建与适配
华为·harmonyos
不爱吃糖的程序媛9 小时前
鸿蒙PC Electron 打印服务实现详解
华为·electron·harmonyos
开源头条12 小时前
2025开源鸿蒙开发者激励计划正式启动,为生态繁荣注入持久动力
华为·开源·harmonyos
奔跑的露西ly15 小时前
【HarmonyOS NEXT】自定义样式复用
华为·harmonyos
lqj_本人15 小时前
HarmonyOS + Cordova:打包发布与环境差异常见问题指南
华为·harmonyos
不羁的木木16 小时前
【开源鸿蒙跨平台开发学习笔记】Day03:React Native 开发 HarmonyOS-GitCode口袋工具开发-1
笔记·学习·harmonyos
lqj_本人16 小时前
鸿蒙Cordova开发踩坑记录:震动反馈的“时差“
华为·harmonyos
lqj_本人18 小时前
鸿蒙原生与Qt混合开发:性能优化与资源管理
qt·harmonyos