在HarmonyOS NEXT开发中new TextAttribute() 会crash,报错TextAttribute is not defined ?

在HarmonyOS NEXT开发中new TextAttribute() 会crash,报错TextAttribute is not defined ?

@Component 
export struct IconFontView { 
  @Prop content: string | null = null; 
  @Prop iconModifier: TextAttribute = new TextAttribute(); 
 private textModifier: TextModifier = new TextModifier(this.iconModifier);

以上写法编译可过,运行时会报错

阅读 1.2k
avatarAI BotBETA

在 HarmonyOS NEXT 的 ArkUI 开发中,TextAttribute 类已被弃用/更名。根据最新 API 变更,应改用 TextStyle 类来实现文本样式属性。正确写法应为:

@Component
export struct IconFontView {
  @Prop content: string | null = null;
  @Prop iconModifier: TextStyle = new TextStyle(); // 替换为 TextStyle
  private textModifier: TextModifier = new TextModifier(this.iconModifier);

需要注意两点变化:

  1. TextAttributeTextStyle 类名变更
  2. 属性初始化方式应改为(避免在声明时直接 new):
aboutToAppear() {
  this.iconModifier = new TextStyle(); // 在生命周期中初始化
}

官方推荐的最新文本样式方案:

Text(this.content)
  .fontSize(20)
  .fontColor(Color.Red)
  .fontStyle(FontStyle.Italic)

建议检查:

  1. 是否导入了正确模块:import { TextStyle } from '@ohos.arkui.text'
  2. SDK 版本是否符合 NEXT 要求(推荐 API 10+)
  3. 编译环境是否清除了旧版本缓存
1 个回答

TextAttribute的用法有误,修改方法如下,请参考文档上用法来写。
文档链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-refere...
可参考buttonAttribute的用法:

class MyButtonModifier implements AttributeModifier<ButtonAttribute> { 
  isDark: boolean = false 
  applyNormalAttribute(instance: ButtonAttribute): void { 
    if (this.isDark) { 
      instance.backgroundColor(Color.Black) 
    } else { 
      instance.backgroundColor(Color.Red) 
    } 
  } 
} 
 
@Entry 
@Component 
struct attributeDemo { 
  @State modifier: MyButtonModifier = new MyButtonModifier() 
 
  build() { 
    Row() { 
      Column() { 
        Button("Button") 
          .attributeModifier(this.modifier) 
          .onClick(() => { 
            this.modifier.isDark = !this.modifier.isDark 
          }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题