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

相关推荐
SuperHeroWu72 小时前
【HarmonyOS AI赋能】朗读控件详解
华为·ai·harmonyos·朗读·赋能·speechkit·场景化语音
大雷神9 小时前
Flutter鸿蒙开发
flutter·华为·harmonyos
●VON12 小时前
重生之我在大学自学鸿蒙开发第二天-《MVVM模式》
学习·华为·harmonyos
安卓开发者13 小时前
鸿蒙NEXT USB Host模式开发完全指南
华为·harmonyos
程序员潘Sir16 小时前
鸿蒙应用开发从入门到实战(二十一):ArkUI自定义弹窗组件
harmonyos·鸿蒙
前端世界17 小时前
从0到1实现鸿蒙智能设备状态监控:轻量级架构、分布式同步与MQTT实战全解析
分布式·架构·harmonyos
2503_9284115617 小时前
10.9 鸿蒙创建和运行项目
android·华为·harmonyos
爱笑的眼睛111 天前
深入浅出ArkTS:HarmonyOS应用开发的现代化语法解析
华为·harmonyos
Kisang.1 天前
【HarmonyOS】窗口管理实战指南
前端·华为·typescript·harmonyos·鸿蒙
it技术2 天前
鸿蒙HarmonyOS实战开发系列课程
harmonyos