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

相关推荐
32 分钟前
鸿蒙——通知
华为·harmonyos·
周胡杰4 小时前
鸿蒙preferences单多例使用,本地存储类
缓存·华为·harmonyos·preferences·鸿蒙本地存储
IvanCodes4 小时前
[鸿蒙2025领航者闯关] 共享终端的隐形守护者:基于 HarmonyOS 6 的全链路隐私闭环实战
华为·harmonyos·鸿蒙
芒鸽9 小时前
鸿蒙PC上FFmpeg+Electron的Encode Smoke(P2) 排错实录:从“无法播放/时长为 0”到“保留画面且转完整时长”
ffmpeg·electron·harmonyos
2501_9444490810 小时前
帮助中心页面 Cordova&OpenHarmony 混合开发实战
harmonyos
搬砖的kk12 小时前
在鸿蒙PC上开发鸿蒙应用:一场从协同到高效的技术之旅
华为·harmonyos
Tipriest_14 小时前
华为鸿蒙/OpenHarmony 的设备调试工具hdc介绍
华为·harmonyos·hdc
轻口味14 小时前
[鸿蒙2025领航者闯关]HarmonyOS 6.0 云台、机械臂等机械体设备与手机交互能力Mechanic Kit介绍
智能手机·交互·harmonyos
SuperHeroWu714 小时前
【HarmonyOS 6】静态和动态添加应用快捷方式详解
华为·源码·harmonyos·快捷方式·动态·静态·代码添加
长弓三石14 小时前
鸿蒙网络编程系列60-仓颉版TLS客户端示例
网络·harmonyos·鸿蒙·仓颉