以下为代码示例:
@Entry @Component struct RichEditorReplaceImageDemo { controller: RichEditorController = new RichEditorController(); @State pictureName: string = ''; @State start: number = 0; // 当前是否输入@符号 @State flag: boolean = false; // 存放图片名称 imageList: Array<string> = ['logo', 'startIcon']; build() { Column() { RichEditor({ controller: this.controller }) .aboutToIMEInput((value: RichEditorInsertValue) => { if (value.insertValue === '@') { this.flag = true; this.start = this.controller.getCaretOffset(); return true; } if (!this.flag) { return true; } // 设置通过空格结束输入图片名 if (value.insertValue === ' ') { // 判断当前图片是否存在 if (this.imageList.includes(this.pictureName)) { this.controller.deleteSpans({ start: this.start, end: this.controller.getCaretOffset() }); this.controller.addImageSpan($r('app.media.' + this.pictureName), { imageStyle: { size: ['100px', '100px'] } }); } // 重置标志符 this.flag = false; this.pictureName = ''; } else { this.pictureName += value.insertValue; } return true; }) .width('98%') .height('30%') .borderWidth(1); } .width('100%') .height('100%'); } }