子組件回調(diào)到父組件的函數(shù)方法

//子組件

@Component export struct sonComponent{

clickBack:()=>void=()=>{ };

build()

?{

Image($r('sys.media.ohos_ic_public_arrow_left')) .width('40') .height('40')

?.onClick((event) =>{this.clickBack(); })?

?}

}

//父組件

@Component

@Entry

export struct father{

clickBack:()=>void=()=>{ };

build() {

Column() {

sonComponent({clickBack:()=>{//調(diào)用父組件的方法}})?

?}

?}

}

注意:子類的?clickBack 千萬不要用@Prop 進(jìn)行修飾。否則會(huì)報(bào)錯(cuò):

Illegal variable value error with decorated variable undefined'clickBack': failed validation:'undefined, null, number, boolean, string, or Object but not function, not V3 @observed / @track class, attempt to assign value type: 'function', value: 'undefined'!

?方法2:使用原生事件進(jìn)行通信eventHub

//父類頁(yè)面進(jìn)行監(jiān)聽事件

@Component

@Entry

struct father{

aboutToAppear():void{

getContext(this).eventHub.on("clickBack",() =>{//調(diào)用父組件的方法})??

}

}

//子組件發(fā)送事件

@Component

export struct sonComponent {

build() {

Column(){

Image($r('sys.media.ohos_ic_public_arrow_left'))? ? ? ? .width('40')? ? ? ? .height('40')? ? ? ?

?.onClick((event) =>{getContext(this).eventHub.emit("clickBack",true)? ? ? ? })??

? }? ?

?}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容