HarmonyOS 鸿蒙Next 自定义组件,@Builder $$按引用传递参数时,在调用时传参,使用箭头函数改变this,该怎么写
HarmonyOS 鸿蒙Next 自定义组件,@Builder $$按引用传递参数时,在调用时传参,使用箭头函数改变this,该怎么写
ScrollContainer是自定义组件
----------------分割线----------------
```ruby
[@Builder](/user/Builder)
content($$: BarData) {
Text($$.navBarHeight+'------------')
}
这样是好使的
build() {
ScrollContainer({
content: this.content
})
}
改变this指向,箭头函数,这样不好使,该怎么写
ScrollContainer({
content: (这里写什么) => {
this.content(这里写什么)
}
})
更多关于HarmonyOS 鸿蒙Next 自定义组件,@Builder $$按引用传递参数时,在调用时传参,使用箭头函数改变this,该怎么写的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
可以使用@BuilderParam
进行重写逻辑
更多关于HarmonyOS 鸿蒙Next 自定义组件,@Builder $$按引用传递参数时,在调用时传参,使用箭头函数改变this,该怎么写的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,使用@Builder
进行自定义组件开发时,如果需要按引用传递参数并在调用时使用箭头函数改变this
的指向,可以按照以下方式编写代码:
@Builder
function MyBuilder($$: { onClick: () => void }) {
Button($$)
.onClick(() => {
$$.onClick();
});
}
@Entry
@Component
struct MyComponent {
private message: string = "Hello, HarmonyOS!";
build() {
Column() {
MyBuilder({
onClick: () => {
this.showMessage();
}
})
}
}
private showMessage() {
console.log(this.message);
}
}
在这个例子中,MyBuilder
是一个自定义的@Builder
函数,它接受一个包含onClick
方法的对象作为参数。在MyComponent
组件中,调用MyBuilder
时传递了一个箭头函数作为onClick
参数,这个箭头函数内部调用了MyComponent
的showMessage
方法。通过这种方式,箭头函数确保了this
指向MyComponent
实例,从而能够正确访问message
属性。
在HarmonyOS鸿蒙Next中,使用@Builder
自定义组件时,若要通过引用传递参数并使用箭头函数改变this
,可以这样写:
@Builder
function customBuilder($$: (arg: any) => void) {
$$(() => {
// 这里的 this 指向当前组件实例
this.someMethod();
});
}
// 调用时
customBuilder((arg) => {
arg(); // 调用箭头函数,保持 this 指向
});
通过箭头函数,确保this
指向当前组件实例,避免上下文丢失。