react+electron实现自定义右键菜单复制粘贴,可以在 electron app 和 其他应用比如 word txt 之间自由复制粘贴。 有啥问题欢迎留言一起讨论
首先上图看效果
情况一
情况二
首先设置自定义菜单 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 import { remote, clipboard } from 'electron' const { Menu, MenuItem } = remotegetContextMenu () { window .addEventListener('contextmenu' , function (e ) { e.preventDefault() let menu = new Menu() menu.append(new MenuItem({ label : '复制' , accelerator : 'CommandOrControl+C' , click : copyString })) menu.append(new MenuItem({ type : 'separator' })) menu.append(new MenuItem({ label : '粘贴' , accelerator : 'CommandOrControl+V' , click : printString })) let flag = false const tagName = document .activeElement.tagName const str = clipboard.readText() const selectStr = _this.getSelection() const text = e.target.innerText || '' const value = e.target.value || '' if (selectStr) { flag = true if (text.indexOf(selectStr) !== -1 || value.indexOf(selectStr) !== -1 ) menu.append(new MenuItem({ label : '复制' , click : copyString })) } if (str && (tagName === 'INPUT' || tagName === 'TEXTAREA' )) { flag = true menu.append(new MenuItem({ label : '粘贴' , click : printString })) } if (flag && (_this.getSelection() || str)) { menu.popup(remote.getCurrentWindow()) } }, false ) function copyString ( ) { const str = getSelection() clipboard.writeText(str) } function printString ( ) { if (document .activeElement) { const str = clipboard.readText() document .activeElement.value = str clipboard.clear() } } } getSelection () { var text = '' if (window .getSelection) { text = window .getSelection().toString() } else if (document .selection && document .selection.type !== 'Control' ) { text = document .selection.createRange().text } if (text) { return text } }
受控组件使用鼠标点击粘贴无法触发onchange问题 这种情况,可以在提交数据时,使用ref方式,直接调用更新数据的方法来实现数据更改, 我是这样写的
1 2 3 4 5 6 7 8 9 10 11 12 13 if (this .acct.value) { this .changeData('username' , this .acct.value) } <input ref={ref => { this .ipt = ref } onChange={evt => changeData('username' , evt.target.value)} />
实现快捷键功能 快捷方式使用 register 方法在 globalShortcut 模块中注册, 即:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import { globalShortcut } from 'electron' globalShortcut.register('CommandOrControl+C' , () => { try { const str = getSelection() clipboard.writeText(str) } catch (e){} }) globalShortcut.register('CommandOrControl+V' , () => { try { const str = clipboard.readText() document .activeElement.value = str clipboard.clear() } catch (e){} })
避免覆盖系统范围的键盘快捷键.
注册全局快捷方式时, 请务必注意目标操作系统中的现有默认值, 以免覆盖任何现有行为.有关每个操作系统键盘快捷键的概述, 请查看这些文档: