页面中实现了一个操作类,包含三个操作方法,并在自定义组件中分别对三个方法进行重写,运行后发现其中某个方法执行的仍是未重写前的操作,问题代码示例参考如下:
// 富文本配置类。 export namespace CRichText { @Observed export class CustomRichController { addImage: (image: string) => void = () => { console.info(`添加图片`); } addVideo: (video: string) => void = () => { console.info(`添加视频`); } setRichText: (data: string) => void = () => { console.info(`设置编辑内容`); } } } @Entry @Component struct Index { @State controller: CRichText.CustomRichController = new CRichText.CustomRichController(); aboutToAppear(): void { this.controller.setRichText('文字'); } build() { Column() { testDemo({ controller: this.controller }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } } @Component struct testDemo { // 自定义组件 @ObjectLink controller: CRichText.CustomRichController; aboutToAppear(): void { // 重写方法 this.controller.addImage = () => { console.info(`出现了图片`); } this.controller.addVideo = () => { console.info(`出现了视频`); } this.controller.setRichText = () => { console.info(`出现了文字`); } } build() { Column() { Text('这是一个测试') .onClick(() => { this.controller.addImage('图片'); this.controller.addVideo('视频'); }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } }
可以从以下三个方面进行排查:
将方法执行放在重写后:
// 富文本配置类。 export namespace CRichText { @Observed export class CustomRichController { addImage: (image: string) => void = () => { console.info(`添加图片`); }; addVideo: (video: string) => void = () => { console.info(`添加视频`); }; setRichText: (data: string) => void = () => { console.info(`设置编辑内容`); }; } } @Entry @Component struct Index { @State controller: CRichText.CustomRichController = new CRichText.CustomRichController(); build() { Column() { testDemo({ controller: this.controller }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } } @Component struct testDemo { // 自定义组件 @ObjectLink controller: CRichText.CustomRichController; aboutToAppear(): void { // 重写方法 this.controller.addImage = () => { console.info(`出现了图片`); }; this.controller.addVideo = () => { console.info(`出现了视频`); }; this.controller.setRichText = () => { console.info(`出现了文字`); }; this.controller.setRichText('文字'); // 将方法调用移动到重写之后 } build() { Column() { Text('这是一个测试') .onClick(() => { this.controller.addImage('图片'); this.controller.addVideo('视频'); }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } }