请参考示例如下:运行后,先输入验证码,删除,再点击临时粘贴控件(PasteButton)import { pasteboard, BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct Index { @State message: string = ''; build() { Row() { Column({ space: 10 }) { TextInput({ placeholder: '请输入验证码', text: this.message }) .onChange((value: string) => { this.message = value; }) PasteButton().onClick((event: ClickEvent, result: PasteButtonOnClickResult) => { if (PasteButtonOnClickResult.SUCCESS === result) { pasteboard.getSystemPasteboard().getData((err: BusinessError, pasteData: pasteboard.PasteData) => { if (err) { console.error(`Failed to get paste data. Code is ${err.code}, message is ${err.message}`); return; } this.message = pasteData.getPrimaryText(); }); } }) Text("复制") .onClick(() => { //剪贴板数据对应的MIME类型,可以是常量中已定义的类型,也可以是自定义的MIME类型,开发者可自定义此参数值, let pasteData: pasteboard.PasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, this.message); let systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard(); systemPasteboard.setData(pasteData, (err, data) => { if (err) { console.error('Failed to set PasteData. Cause: ' + err.message); return; } console.info('Succeeded in setting PasteData.'); }); }) } .width('100%') } .height('100%') } }点击复制我,弹窗复制成功,退出找个记事本,点击粘贴,显示成功import pasteboard from '@ohos.pasteboard' import promptAction from '@ohos.promptAction' @Entry @Component export struct CopyText { private textContent: string = "复制我" build() { Column() { Text(this.textContent) .fontSize($r("sys.float.ohos_id_text_size_body3")) .borderRadius(9) .borderWidth(1) .padding({ left: 8, right:8}) .fontColor($r('sys.color.ohos_id_color_text_primary')) .fontWeight(FontWeight.Medium) .opacity($r("sys.float.ohos_id_alpha_content_secondary")) .onClick(() => copyText(this.textContent)) } } } function copyText(text: string) { const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text) const systemPasteboard = pasteboard.getSystemPasteboard() systemPasteboard.setData(pasteboardData) // 将数据放入剪切板 systemPasteboard.getData().then((data) => { if (data) { promptAction.showToast({ message: "复制成功" }) } else { promptAction.showToast({ message: "复制失败" }) } }) }
请参考示例如下:
运行后,先输入验证码,删除,再点击临时粘贴控件(PasteButton)
点击复制我,弹窗复制成功,
退出找个记事本,点击粘贴,显示成功