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

相关推荐
浮芷.2 分钟前
Flutter 框架跨平台鸿蒙开发 - 科技预言应用
科技·flutter·华为·harmonyos
李李李勃谦8 分钟前
Flutter 框架跨平台鸿蒙开发 - 小众景点发现
flutter·华为·harmonyos
见山是山-见水是水8 分钟前
Flutter 框架跨平台鸿蒙开发 - 邻里互助服务平台
flutter·华为·harmonyos
提子拌饭13315 分钟前
3D 旋转卡片:鸿蒙Flutter 实现的交互式 3D 卡片效果
flutter·华为·harmonyos·鸿蒙
提子拌饭13315 分钟前
星芒便签:鸿蒙Flutter框架 实现的美观便签应用
flutter·华为·架构·开源·harmonyos·鸿蒙
一直在想名18 分钟前
Flutter 框架跨平台鸿蒙开发 - 亲子故事共创
flutter·华为·harmonyos
2401_8396339118 分钟前
Flutter 框架跨平台鸿蒙开发 - 声音密码锁
服务器·flutter·华为·harmonyos
Utopia^19 分钟前
Flutter 框架跨平台鸿蒙开发 - 知识卡片整理
flutter·华为·harmonyos
@不误正业31 分钟前
第04章-开源鸿蒙的架构概览
架构·开源·harmonyos
独特的螺狮粉32 分钟前
开源鸿蒙跨平台Flutter开发:近视防控数字疗法:基于 Flutter 的眼动物理追踪与睫状肌动力学舒缓测绘架构
flutter·华为·架构·开源·harmonyos·鸿蒙