页面结构和方法:
<Button style = {{ color: "blue", border: "none" }} type = "link" id = "btn" ref = { copy => (this.copy = copy) } onClick = { this.copyInputValue } className = "copy" > 复制 </Button> //复制按钮
< Input type = "text" id = "inputText" ref = { input => (this.inputText = input) } value = { this.state.value } readOnly / > // input框
// 点击复制按钮
copyInputValue () => {
const inputText = document.getElementById("inputText"); // 获取要被拷贝的值的dom对象
const currentFocus = document.activeElement; // 获取页面上正在被选中的对象
inputText.focus();
inputText.setSelectionRange(0, inputText.value.length); // 方法可以从一个被 focused 的 <input> 元素中选中特定范围的内容。
document.execCommand("copy", true);
currentFocus.focus();
}