首先需要这样一个函数

function copyText(text: string) {
  const uiContext: UIContext | undefined = AppStorage.get('context');
  const pasteboardData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
  const systemPasteboard = pasteboard.getSystemPasteboard();
  systemPasteboard.setData(pasteboardData); // Put data into clipboard
  systemPasteboard.getData().then((data) => { // Read clipboard content
    if (data) {
      uiContext?.getPromptAction().showToast({ message: 'Copy succeeded' });
    } else {
      uiContext?.getPromptAction().showToast({ message: 'Copy failed' });
    }
  })
}

然后绑定一个事件

.onClick(() => copyText(this.textContent))

ok了

记得导入

import { pasteboard } from '@kit.BasicServicesKit';

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐