HarmonyOS 组件封装如何可选调用链式属性方法?

我要封装系统Text,封装它所有的链式属性方法。但是我传入的参数是可选的,链式属性方法的值是必选的,我如何判断自己的参数在undefined时,不去调用链式属性方法。

比如想要fontSize为undefined时不调用.fontSize()方法,直接用Text自己的默认值,这种逻辑要怎么写?能实现吗?

看@Style和@Extend好像都不支持

@Component
export struct AAText {
  fontSize?: number | undefined
  build() {
    Text()
      .fontSize(this.fontSize) // 如果this.fontSize == undefined,则不传值,使用Text默认值
  }
}
阅读 470
1 个回答

UI描述需要遵循以下规则:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-create-custom-components-V5\#build函数

不允许使用表达式,可以参考渲染控制:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-rendering-control-ifelse-V5

if(this.shouldSetBackgroundColor){
  Text('Top True, Nested True, positive COLOR Nested ')
    .backgroundColor(Color.Red)
}else{
  Text('Top True, Nested True, positive COLOR Nested ')
}

属性多的话可以使用@Style装饰器简化

@Style baseStyle() {}
@Style condAStyle() {}
@Style condBStyle() {}
if(condA) {
  Text().baseStyle().condAStyle()
} else {
  Text().baseStyle().condBStyle()
}

或者可以使用动态属性设置的方法,根据需要使用多态样式设置属性。要简洁很多

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-attributes-attribute-modifier-V5

公用组件封装可以参考此文档:https://developer.huawei.com/consumer/cn/doc/best-practices-V5/bpta-ui-component-encapsulation-V5\#section398883112484

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进