From 147318e3d8241cf389609fda1b1f98c818229eac Mon Sep 17 00:00:00 2001 From: puyajun Date: Mon, 7 Feb 2022 10:35:21 +0800 Subject: [PATCH] puyajun@huawei.com Signed-off-by: puyajun --- .../ui/ts-component-based-builder.md | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/zh-cn/application-dev/ui/ts-component-based-builder.md b/zh-cn/application-dev/ui/ts-component-based-builder.md index 5c0b80f3017..d74afdad4c4 100644 --- a/zh-cn/application-dev/ui/ts-component-based-builder.md +++ b/zh-cn/application-dev/ui/ts-component-based-builder.md @@ -39,4 +39,99 @@ struct CompA { } } ``` +## @BuilderParam8+ +@BuilderParam装饰器用于修饰自定义组件内函数类型的属性,并且在创建自定义组件时使用@BuilderParam修饰的属性必须赋值。 + +### 引入动机 + +当开发者创建定义组件后只能对@Builder修饰的方法进行调用,不能扩展。如:一个组件内多次调用了@Builder修饰的方法,如果在某一个调用内添加点击事件,若在方法内添加就会导致所有的调用都添加点击事件。为解决此问题引入了@BuilderParam装饰器,此装饰器修饰的属性值可为@Builder修饰的方法,开发者可在对属性赋值时进拓展操作。 + +### 场景一 +将@Builder装饰的方法赋值给@BuilderParam修饰的属性,并在自定义组件内进行调用。 +``` +@Component +struct CustomContainer { + header: string = ""; + @BuilderParam content: () => any; + footer: string = ""; + build() { + Column() { + this.content() + Text(this.header) + .fontSize(50) + Text(this.footer) + .fontSize(50) + } + } +} + +@Entry +@Component +struct CustomContainerUser { + @Builder specificParam(label1: string, label2: string) { + Column() { + Text(label1).fontSize(50) + Text(label2).fontSize(50) + } + } + + build() { + Column() { + CustomContainer({ + header: "Header", + footer: "Footer", + content: this.specificParam("11", "22") + }) + } + } +} +``` +### 场景二 +在自定义组件中使用@BuilderParam修饰的属性接收尾随闭包(在实例化自定义组件时后面紧跟一个大括号“{}”形成尾随闭包场景。如:CustomComponent(){})的内容,在尾随闭包内可进行自定义组件的拓展,如在当前实例化自定义组件时可在闭包内增加Text组件,但在另一处可增加一个Text组件并添加点击事件,并且闭包内语法规范与[build](../ui/ts-function-build.md)一致。此场景下自定义组件内有且仅有一个使用@BuilderParam修饰的属性。 + +示例:在闭包内增加Column组件并添加一个点击事件,在新增的Column组件内调用@Builder修饰的specificParam方法,点击Column组件后改变自定义组件中的header的属性值为“changeHeader”。并且在实例化自定义组件时会把尾随闭包的内容赋值给@BuilderParam修饰的closeContent属性。 +``` +@Component +struct CustomContainer { + header: string = ""; + @BuilderParam closeContent: () => any; + footer: string = ""; + build() { + Column() { + this.closeContent() + Text(this.header) + .fontSize(50) + Text(this.footer) + .fontSize(50) + } + } +} +@Builder function specificParam(label1: string, label2: string) { + Column() { + Text(label1) + .fontSize(50) + Text(label2) + .fontSize(50) + } +} +@Entry +@Component +struct CustomContainerUser { + @State text: string = "header" + build() { + Column() { + CustomContainer({ + header: this.text, + footer: "Footer" + }){ + Column(){ + specificParam("111", "22") + }.onClick(()=>{ + this.text = "changeHeader" + }) + } + } + } +} +``` -- Gitee