记录日常,防止忘记
(1)通过设置 RichEditor 组件的 onSelectionChange 属性对光标位置进行更新,方便后续插入组件。
(2)通过在 onClick 函数里面定义局部变量,记录光标位置也可以直接作为插入偏移量(更直接)。
【1】代码:
@ComponentV2
struct CustomEditorComponent {
richEditorController: RichEditorController = new RichEditorController();
basedOnSpanEditorController: RichEditorOptions = { controller: this.richEditorController };
private myBuilder: CustomBuilder = undefined;
private selection = this.basedOnSpanEditorController.controller.getCaretOffset();
@Builder
CustomComponent(text: string) {
Row() {
Text(text)
}
.justifyContent(FlexAlign.Center)
.alignItems(VerticalAlign.Center)
.width(120)
.height(40)
.margin({
left: 3,
right: 3
})
.borderRadius(16)
.backgroundColor('#ffffff')
}
build() {
Column({ space: 20 }) {
Row() {
Button('添加自定义组件')
.fontColor('#ffffffff')
.fontWeight(600)
.type(ButtonType.Normal)
.borderRadius(12)
.backgroundColor('#ff0ea4b3')
.onClick(() => {
this.myBuilder = () => { this.CustomComponent('自定义组件'); }
// 拿到光标位置进行插入
this.basedOnSpanEditorController.controller.addBuilderSpan(this.myBuilder, {
offset: this.selection
});
})
}
.padding({ left: 10 })
.width('90%')
.height(60)
.borderRadius(16)
.backgroundColor('#ffe9e9e9')
RichEditor(this.basedOnSpanEditorController)
.width('100%').height('50%')
.borderRadius(8)
.backgroundColor('#ffd9cbb3')
.padding({
top: 15,
left: 10, right: 10,
bottom: 15
})
// 更新光标位置
.onSelectionChange(() => {
this.selection = this.basedOnSpanEditorController.controller.getCaretOffset();
})
}
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.width('100%')
.height('100%')
.padding(20)
.backgroundColor(Color.White)
}
}
【2】代码:
Row() {
Button('添加自定义组件')
.fontColor('#ffffffff')
.fontWeight(600)
.type(ButtonType.Normal)
.borderRadius(12)
.backgroundColor('#ff0ea4b3')
.onClick(() => {
// 定义局部变量记录光标位置
let insertOffset = this.richEditorController.getCaretOffset();
this.myBuilder = () => { this.CustomComponent('自定义组件'); }
// 拿到光标位置进行插入
this.basedOnSpanEditorController.controller.addBuilderSpan(this.myBuilder, {
offset: insertOffset
});
})
}
效果:





































苏公安网备 32011402010933号
学习一下