在查看common.d.ts声明文件的时候发现有两个文档上没见过的变量

/**
* Defining BuilderParam PropertyDecorator
* @since 7
*/
declare const BuilderParam: PropertyDecorator;

/**
* Defining Styles MethodDecorator
* @since 8
*/
declare const Styles: MethodDecorator;

@BuilderParam 是一个变量装饰器

@Styles 是一个方法装饰器

@BuilderParam

这个装饰器有什么用呢,我们来看一段这样的代码。

使用IDE: DevEco Studio 3.0 Beta3

eTS的自定义组件似乎没有为我们供Slot插槽,如果我们给自定义组件加上一个大括号和子组件会怎么样呢?

@Component
struct TestComponent {
build() {
Column() {}
}
}

@Entry
@Component
export struct MainPage {
build() {
Column() {
TestComponent() {
Text('aaaaaaaaaaaa').fontSize(30)
}
}
.height('100%')
.width('100%')
}
}

刷新Previewer会发现报错了。

查看PreviewerLog:

【OpenHarmony应用开发】eTS装饰器 @BuilderParam与@Styles_OpenHarmony

在这里我们很明显发现了一个关键词@BuilderParam。那么我们尝试给自定义组件TestComponent添加一个装饰器方法并试着执行他。

@Component
struct TestComponent {
@BuilderParam builder:()=>{}

build() {
Column() {
this.builder()
}
}
}

刷新Previewer

【OpenHarmony应用开发】eTS装饰器 @BuilderParam与@Styles_@Styles_02

居然成功了!去真机上确定下效果。

【OpenHarmony应用开发】eTS装饰器 @BuilderParam与@Styles_@BuilderParam_03

看来以后再也不需要ForEach来实现插槽了

注意:一个组件内只允许有一个@BuilderParam装饰器

【补充】刚发现一个问题 @BuilderParam 装饰器与 @Link 装饰器无法同时存在,待研究

@BuilderParam还有个有趣的地方,如果我们想办法把他打印出来,会发现不论我们之前给他定义成什么数据类型,他都会是一个方法。

@Component
struct TestComponent {
@BuilderParam builder: string

build() {
Scroll() {
Text(this.builder.toString()).fontSize(20)
}
.height('100%')
.width('100%')
}
}

效果:

【OpenHarmony应用开发】eTS装饰器 @BuilderParam与@Styles_OpenHarmony_04

@Styles

这个是API8 提供的一个新的装饰器,我们知道@Extend装饰器不能写在组件内,但@Styles却能够定义在组件内。

@Styles和@Extend一样,也是提供方法将新的属性函数添加到内置组件。

在验证中发现了几个注意的点:

  • @Styles装饰的方法不能带参数
  • 组件内@Styles装饰的方法可以有多个
  • 后面执行的属性函数优先级最高
@Component
struct TestComponent {
@BuilderParam builder:()=>{}

@Styles backgroundRed(){
.backgroundColor(Color.Red)
.width(300)
.height(100)
}

build() {
Column() {
this.builder()
}
.backgroundRed()
}
}

效果:

【OpenHarmony应用开发】eTS装饰器 @BuilderParam与@Styles_OpenHarmony_05

@Component
struct TestComponent {
@BuilderParam builder:()=>{}

@Styles backgroundRed(){
.backgroundColor(Color.Red)
.width(300)
.height(100)
}

@Styles backgroundBlue(){
.backgroundColor(Color.Blue)
}

build() {
Column() {
this.builder()
}
.backgroundRed()
.backgroundBlue()
}
}

效果:

【OpenHarmony应用开发】eTS装饰器 @BuilderParam与@Styles_@Styles_06

如果自定义组件也能有自己的属性函数就更好了