文档管理中心
您当前正在浏览HarmonyOS最新文档,覆盖已发布的所有API版本,可在API参考中筛选您使用的API版本。详细的版本配套关系请参考版本说明
开发与测试开放能力API应用框架ArkUI(方舟UI框架)ArkTS组件通用属性动态属性与自定义属性操作工具

属性操作工具

Phone26.0.0+PC/2in126.0.0+Tablet26.0.0+TV26.0.0+Wearable26.0.0+

ModifierUtils

Phone26.0.0+PC/2in126.0.0+Tablet26.0.0+TV26.0.0+Wearable26.0.0+

ModifierUtils是一个属性修改器工具类,用于提供属性操作的方法。例如,可以判断给定的实例是否为指定组件类型,适用于在统一的AttributeModifier中需要区分不同组件类型并进行差异化属性设置的场景。

起始版本: 26.0.0

元服务API: 从API版本26.0.0开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

模型约束: 此接口仅可在Stage模型下使用。

isInstanceOf<T extends CommonMethod<T>>

Phone26.0.0+PC/2in126.0.0+Tablet26.0.0+TV26.0.0+Wearable26.0.0+

isInstanceOf<T extends CommonMethod<T>>(instance: T, componentName: string): boolean

检查给定的实例是否为指定组件类型。例如,在自定义属性修改器(AttributeModifier)中为多种组件类型实现统一的属性修改逻辑时,可通过该方法判断当前实例的组件类型,从而对不同组件应用不同的属性设置。

起始版本: 26.0.0

元服务API: 从API版本26.0.0开始,该接口支持在元服务中使用。

系统能力: SystemCapability.ArkUI.ArkUI.Full

模型约束: 此接口仅可在Stage模型下使用。

参数:

展开
参数名 类型 必填 说明
instance T 要检查的实例,T为继承自通用属性(CommonMethod)的组件属性类型。
componentName string 要检查的组件类型名称,取值为组件类名(如 'Text'、'Button' 等),需与组件类名完全一致(区分大小写)。传入无效或不存在的组件类名时返回false。

返回值:

展开
类型 说明
boolean 如果实例是指定的组件类型,则返回true;否则返回false。

示例:

收起
自动换行
深色代码主题
复制
  1. // xxx.ets
  2. // 点击按钮,并检查日志,判断组件是否进入独有分支
  3. import { ModifierUtils } from '@kit.ArkUI';
  4. class MyModifier implements AttributeModifier<TextAttribute | ButtonAttribute> {
  5. isDark: boolean = false;
  6. constructor(dark?: boolean) {
  7. this.isDark = dark ?? false;
  8. }
  9. applyNormalAttribute(instance: TextAttribute | ButtonAttribute): void {
  10. if (ModifierUtils.isInstanceOf(instance, 'Text')) {
  11. console.info('This is TextAttribute');
  12. const textInstance = instance as TextAttribute;
  13. if (this.isDark) {
  14. textInstance.backgroundColor(Color.Blue);
  15. } else {
  16. textInstance.backgroundColor(Color.Green);
  17. }
  18. } else if (ModifierUtils.isInstanceOf(instance, 'Button')) {
  19. console.info('This is ButtonAttribute');
  20. const buttonInstance = instance as ButtonAttribute;
  21. if (this.isDark) {
  22. buttonInstance.type(ButtonType.Circle);
  23. buttonInstance.backgroundColor(Color.Blue);
  24. } else {
  25. buttonInstance.type(ButtonType.Normal);
  26. buttonInstance.backgroundColor(Color.Green);
  27. }
  28. }
  29. }
  30. }
  31. @Entry
  32. @Component
  33. struct MultiComponentAttributeDemo {
  34. @State myModifier: MyModifier = new MyModifier();
  35. build() {
  36. Column() {
  37. Text('Text')
  38. .fontSize(50)
  39. .attributeModifier(this.myModifier)
  40. .onClick(() => {
  41. this.myModifier.isDark = !this.myModifier.isDark;
  42. })
  43. Button('Button')
  44. .attributeModifier(this.myModifier)
  45. .onClick(() => {
  46. this.myModifier.isDark = !this.myModifier.isDark;
  47. })
  48. }
  49. .justifyContent(FlexAlign.SpaceEvenly)
  50. .width('100%')
  51. .height('50%')
  52. }
  53. }
在 开发与测试 开放能力API 中进行搜索
请输入您想要搜索的关键词