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

相关推荐
程序猿追5 分钟前
HarmonyOS 7 多标签草稿,关掉当前页之后该留下谁
pytorch·深度学习·harmonyos
默 语2 小时前
HarmonyOS7基础属性全解(六):浮层 overlay——角标水印挂上去,容器层级一点不加
harmonyos
默 语4 小时前
HarmonyOS7基础属性全解-组件标识id
harmonyos
默 语4 小时前
HarmonyOS7基础属性全解(八):隐私遮罩 obscured——屏幕上看得清清楚楚,录屏里只剩占位图
wpf·harmonyos
默 语4 小时前
HarmonyOS7基础属性全解(五):背景设置——颜色垫底、图片其上、模糊封顶
harmonyos
默 语4 小时前
HarmonyOS7基础属性全解(七):Z序控制 zIndex——谁浮在上面,代码说了算
harmonyos
ovenslove8 小时前
权限申请:为什么你的相机打不开
harmonyos·arkts
NJPJI_Yang8 小时前
鸿蒙操作系统使用 Media Library Kit 实现媒体库资源保存与查询实战(本文已在AtomGit仓库开源)
华为·开源·harmonyos
OH_TPC8 小时前
@ohos/grpc 源码解读(二):四种 RPC 模式的流状态机——EOF、DEFERRED 与 wakeupPipe 的分工
harmonyos
行者-全栈开发13 小时前
【鸿蒙心迹】性能常态化检测——内存 / CPU / 帧率三件套怎么建基线、设门禁(HarmonyOS 7.x)
harmonyos·内存泄漏·cpu占用·ci门禁·性能检测·帧率监控·性能基线