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

相关推荐
__Benco2 小时前
OpenHarmony平台驱动开发(十七),UART
人工智能·驱动开发·harmonyos
落叶挽歌12 小时前
鸿蒙ArkUI体验:Hexo博客客户端开发心得
华为·harmonyos
特立独行的猫a12 小时前
uni-app 开发HarmonyOS的鸿蒙影视项目分享:从实战案例到开源后台
uni-app·开源·harmonyos·鸿蒙·影视
交叉编译之王 hahaha14 小时前
RK3568-鸿蒙5.1镜像烧录与调试
华为·harmonyos
Raink老师14 小时前
鸿蒙页面布局入门
华为·harmonyos·鸿蒙·移动端布局
hbcui198415 小时前
uni-app x正式支持鸿蒙原生应用开发
uni-app·harmonyos·uni-app x
lqj_本人15 小时前
鸿蒙OS&UniApp制作支持多图上传的图片选择器:打造高性能移动端上传体验#三方框架 #Uniapp
华为·uni-app·harmonyos
晚秋大魔王16 小时前
OpenHarmony 开源鸿蒙南向开发——linux下使用make交叉编译第三方库——wget
java·linux·运维·开发语言·华为·harmonyos
周胡杰1 天前
组件导航 (HMRouter)+flutter项目搭建-混合开发+分栏效果
前端·flutter·华为·harmonyos·鸿蒙·鸿蒙系统
bestadc1 天前
鸿蒙 Core File Kit(文件基础服务)之简单使用文件
harmonyos