我说的这个问题是基于antd design的react的Table。 但是我感觉我的解决思路是有异曲同工之处的,大家可以借鉴一下。
知识点(不懂的,可以直接复制百度)
1.window.getSelection()
(返回一个 Selection 对象,表示用户选择的文本范围或光标的当前位置。)
2.event.button
获取鼠标点击的是左键还是右键。 结果"0"代表左键,"2"代表右键。
3.sessionStorage
用来存储临时的数据,会话结束 ,数据销毁。
4.CommonUtils.StringIsEmpty()
这个是我们自己封装的一个用来判断字符串是否为空的。
思路
1.用onclick来判断鼠标按键(按键有 左按键还是右按键的区别,需要根据event.button判断一下)松开后是否有内容(window.getSelection()来获取选择的内容)。
2.在上一步的基础上,判断一下是否内容
(1)一种是没有内容,说明用户想做一个行点击事件,执行行点击事件即可。
(2)一种是有内容,在有内容的基础上,又分为两种情况
(3)一种是用户不小心选中内容,因此在选中内容的基础上,又执行了行点击事件。
(4)一种是用户真的想复制内容。
那么针对(3)中所说的情况,我们要从整体考虑一下,选择内容,执行第一步的onclick,在选中内容的基础上,怎么知道他想执行行点击呢,这就用到了sessionStorage,可以在第一次执行onmouseup的时候给他一个Table中的rowKey。用来区分是第几次进入onclick,当然在第二次进入onclick也就是执行行点击事件的时候把sessionStorage清空
那么针对(4)中所说的情况,在第一次进入onclick的基础上,运用event.button得知,右键复制。然后清空window.getSelection()和sessionStorage的内容
备注:当你连续两次在同一行选择内容,因为你的rowKey的都是同一个。因此你可以通过前后两次选择的内容是否不同来区分。
代码
<Table
id={"myAssets"}
rowKey={record => record.id}
onRow={record => {
return {
onclick: event => {
function enter() {
window.getSelection().removeAllRanges()
sessionStorage.removeItem('id');
sessionStorage.setItem("assetsId", record.id);
sessionStorage.setItem("ownerId", record.ownerid);
const isOwner = record.ownerid === record.accountid
sessionStorage.setItem("showOtherOption", isOwner.toString());
history.push('/myassets/myassets-detail');
}
if (event.button === 0) {
const selection = window.getSelection();
if (CommonUtils.StringIsEmpty(selection.toString())) {
enter();
} else {
const id = sessionStorage.getItem("id");
const copyContent = sessionStorage.getItem("copyContent");
const selection = window.getSelection();
if (id === record.id&&selection.toString()===copyContent) {
enter();
} else {
const selection = window.getSelection();
sessionStorage.setItem("id", record.id);
sessionStorage.setItem("copyContent", selection.toString());
}
}}
if (event.button === 2) {
document.getElementById("myAssets").oncopy = function () {
document.getElementById("myAssets").onpaste=function(){
window.getSelection().removeAllRanges();
sessionStorage.removeItem('id');
}
}
document.getElementById("myAssets").oncut = function () {
document.getElementById("myAssets").onpaste=function(){
window.getSelection().removeAllRanges();
sessionStorage.removeItem('id');
}}}
},
onDoubleClick: event => { }
};
}}
>
备注:function enter()是用来执行行点击跳转的。