//子組件
@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)? ? ? ? })??
? }? ?
?}
}