Harmony状态管理@Local和@Param

2025-06-24 22:04:18
174次阅读
0个评论

深入理解ArkUI中的@Param与@Local装饰器

引言

在ArkUI的状态管理系统中,@Param和@Local是两个核心装饰器,它们分别用于处理组件间的数据传递和组件内部状态管理。本文将详细介绍这两个装饰器的使用场景、特性差异以及最佳实践。

@Param装饰器:组件外部输入

@Param装饰器用于增强子组件接受外部参数输入的能力,支持数据同步变化,并允许在组件间进行数据传递与同步。

核心特性

  1. 外部输入:@Param表示组件从外部传入的状态
  2. 同步机制:当数据源也是状态变量时,数据源的修改会同步给@Param
  3. 类型支持:支持number、boolean、string、Object、class等基本类型以及Array、Set、Map、Date等内嵌类型
  4. 观测能力:装饰的变量变化时,会刷新该变量关联的组件

基本用法示例

@ComponentV2
struct ChildComponent {
  @Param message: string = 'default';
  
  build() {
    Text(this.message)
  }
}

@Entry
@ComponentV2
struct ParentComponent {
  @Local parentMessage: string = 'Hello from parent';
  
  build() {
    Column() {
      ChildComponent({ message: this.parentMessage })
    }
  }
}

高级特性

  1. 联合类型支持
@Param count: number | undefined = 0;
  1. 对象属性修改
// 可以修改对象属性,会同步到父组件
@Param info: Info;
Button('Change name').onClick(() => {
  this.info.name = 'New Name';
})

@Local装饰器:组件内部状态

@Local装饰器用于在@ComponentV2装饰的自定义组件中表示内部状态,使变量具有观测变化的能力。

核心特性

  1. 内部状态:只能在组件内部初始化,不允许外部传入
  2. 变化观测:变量变化时会触发UI刷新
  3. 类型支持:支持多种数据类型,但对深层对象属性的观测需依赖@ObservedV2和@Trace装饰器

基本用法示例

@Entry
@ComponentV2
struct Counter {
  @Local count: number = 0;
  
  build() {
    Column() {
      Text(`Count: ${this.count}`)
      Button('Increment').onClick(() => {
        this.count++;
      })
    }
  }
}

高级用法

  1. 复杂类型处理
@ObservedV2
class User {
  @Trace name: string;
  @Trace age: number;
}

@Entry
@ComponentV2
struct UserProfile {
  @Local user: User = new User('Alice', 25);
  
  build() {
    Column() {
      Text(`Name: ${this.user.name}`)
      Text(`Age: ${this.user.age}`)
      Button('Increase Age').onClick(() => {
        this.user.age++;
      })
    }
  }
}

@Param与@Local对比

特性 @Param @Local
初始化来源 外部传入或本地默认值 必须本地初始化
同步方向 父到子单向同步 仅组件内部
可观测性 观测变量本身 观测变量本身
修改权限 子组件不可直接修改(除非@Once) 组件内可自由修改
使用场景 组件间数据传递 组件内部状态管理
复杂类型支持 支持,需配合@ObservedV2/@Trace 支持,需配合@ObservedV2/@Trace

实际应用场景

场景1:表单组件

// 父组件
@Entry
@ComponentV2
struct FormPage {
  @Local formData: FormData = new FormData();
  
  build() {
    Column() {
      FormInput({ data: this.formData.username })
      FormInput({ data: this.formData.password })
      SubmitButton({ formData: this.formData })
    }
  }
}

// 子输入组件
@ComponentV2
struct FormInput {
  @Param data: string = '';
  
  build() {
    TextInput(this.data)
  }
}

场景2:列表项状态管理

@ObservedV2
class TodoItem {
  @Trace text: string;
  @Trace completed: boolean;
}

@Entry
@ComponentV2
struct TodoList {
  @Local items: TodoItem[] = [
    new TodoItem('Buy milk'),
    new TodoItem('Call mom')
  ];
  
  build() {
    List() {
      ForEach(this.items, (item) => {
        ListItem() {
          TodoItemComponent({ item: item })
        }
      })
    }
  }
}

@ComponentV2
struct TodoItemComponent {
  @Param item: TodoItem;
  
  build() {
    Row() {
      Text(this.item.text)
        .decoration({ 
          type: this.item.completed ? 
            TextDecorationType.LineThrough : 
            TextDecorationType.None 
        })
      Checkbox(this.item.completed)
        .onChange((checked) => {
          this.item.completed = checked;
        })
    }
  }
}

最佳实践

  1. 合理选择装饰器
    • 需要从父组件接收数据时使用@Param
    • 纯内部状态管理使用@Local
  2. 复杂类型处理
    • 对于嵌套对象,使用@ObservedV2和@Trace确保深度观测
  3. 性能优化
    • 避免在@Param和@Local中存储过大对象
    • 对于频繁变化的复杂数据,考虑使用@Computed计算属性
  4. 代码组织
    • 将@Local状态变量集中在组件顶部声明
    • 为@Param提供合理的默认值

常见问题解决

问题1:为什么子组件修改@Param变量不生效?

解决方案:@Param默认是只读的,如果需要修改,可以:

  1. 使用@Param @Once组合
  2. 通过事件通知父组件修改
  3. 修改对象属性而非对象本身

问题2:如何深度观测嵌套对象?

解决方案:使用@ObservedV2和@Trace装饰器:

@ObservedV2
class DeepObject {
  @Trace nested: {
    @Trace deepValue: string;
  };
}

总结

@Param和@Local是ArkUI状态管理的两大基石,理解它们的特性和适用场景对于构建可维护、高性能的ArkUI应用至关重要。@Param实现了组件间的数据流动,而@Local管理了组件内部的状态生命周期。合理运用这两个装饰器,结合@ObservedV2和@Trace等辅助装饰器,可以构建出响应式、结构清晰的UI组件。

收藏00

登录 后评论。没有帐号? 注册 一个。