HarmonyOS 鸿蒙Next中如何传递函数
HarmonyOS 鸿蒙Next中如何传递函数
@Component export struct Parent { handleClick() { console.log(1) }
build(){
Child({
handleClick: this.handleClick.bind(this)
})
}
}
@Component export struct Child { @Prop handleClick() { console.log(1) }
build(){
Text('11').onClick(this.handleClick)
}
}
这样传递会报错Illegal variable value error with decorated variable @Prop ‘handleClick’: failed validation: 'undefined, null, number, boolean, string, or Object but not function, not V2 @ObservedV2 / @Trace class, and makeObserved return value either, and attempt to assign value type: ‘function’, value: ‘undefined’!
@Prop不支持接收函数,那应该如何接收呢
更多关于HarmonyOS 鸿蒙Next中如何传递函数的实战教程也可以访问 https://www.itying.com/category-93-b0.html
【解决方案】
@Component自定义组件支持创建通信事件,完成父子组件的通信。 方案如下:
-
父组件调用子组件
-
子组件调用父组件
[@Component](/user/Component)
struct Child {
@State private text: string = '子组件的值'
private controller: ChildController = new ChildController();
aboutToAppear() {
if (this.controller) {
this.controller.changeText = this.changeText
}
}
changeText(value: string){
this.text = value
}
build() {
Column() {
Text(this.text)
}
}
}
class ChildController {
changeText = (value: string) => {
console.log(value)
}
}
export let ChildRef = new ChildController()
@Entry
[@Component](/user/Component)
struct Parent {
@State noShow: boolean = false
build() {
Column() {
Text('获取Child的方法').fontSize(18).fontColor("#f1f3f5")
Divider()
Child({ controller: ChildRef })
Child()
Button('调用childer的changeText') onClick={() => {
ChildRef.changeText('调用childer的changeText')
}}
}
}
}
[@Component](/user/Component)
struct Child {
onClickOK?: () => void;
build() {
Row() {
Column() {
Button('事件').onClick(() => {
if (this.onClickOK !== undefined) {
this.onClickOK()
}
})
}.width('100%')
}.height('100%')
}
}
更多关于HarmonyOS 鸿蒙Next中如何传递函数的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS(鸿蒙)Next中,传递函数可以通过将函数作为参数传递给其他函数或方法来实现。以下是一个简单的示例:
function greet(name: string): void {
console.log(`Hello, ${name}!`);
}
function executeFunction(func: (name: string) => void, name: string): void {
func(name);
}
executeFunction(greet, "Alice");
在这个示例中,greet
函数被作为参数传递给executeFunction
,并在其中被调用。这种方式在回调、事件处理等场景中非常常见。