利用的插件包 clipboard-polyfill
1 import React, { Component } from 'react'
2
3 import clipboard from "clipboard-polyfill"
4 import {Button} from "antd"
5
6 export default class Main extends Component {
7 constructor(props){
8 super(props);
9 this.state={
10 opj:{
11 "param.code.name":"姓名",
12 "param.codexname":"昵称",
13 "param.code.age":"年龄",
14 "param.code.gender":"性别",
15 "param.code.hobby":"爱好",
16 },
17 val:"大家好这是新来的同学,叫 ,也可以叫,今年了,喜欢,也喜欢",
18 changeVal:""
19 }
20 }
21 render() {
22 //console.log(Object.entries(this.state))
23 return (
24 <div>
25 <div className="top">
26 {Object.entries(this.state.opj).map((item,index)=>{
27 return <Button className="btn" key={index} onClick={this.copy.bind(this,index,item)}>{item[1]}</Button>
28 })}
29 </div>
30 <textarea name="" id="text" ref="text" onPaste={this.paste.bind(this)} cols="30" rows="10" value={this.state.val} onChange={(e)=>{
31 this.setState({
32 val:e.target.value
33 })
34 }} />
35 <button onClick={this.del.bind(this)}>去除value</button>
36 <button onClick={this.add.bind(this)}>补充value</button>
37 </div>
38 )
39 }
40 copy(index,item){
41 //document.execCommand("Copy"); // 执行浏览器复制命令
42 // let btn=document.querySelectorAll(".btn")[index]
43 // btn.value=`[${item[1]}(${item[0]})]`
44 // btn.select()
45 // console.log(document.execCommand("Copy"))
46 // btn.value=item[1]
47
48 let text=`[${item[1]}(${item[0]})]`;
49 //将文字复制到剪贴板
50 clipboard.writeText(text)
51 //console.log(text);
52 }
53 del(){
54 let str=this.state.val;
55 str=str.replace("]","")
56 let res=/[.*?(/g;
57 str=str.replace(res,"(")
58 //console.log(str);
59 this.setState({
60 val:str
61 })
62 }
63 add(){
64 let str=this.state.val;
65 if(str.indexOf("]")<0){
66 console.log(111)
67 str=str.replace(/((.+?))/g, ($0,$1,$2)=> {
68 console.log($0,$1,$2,"============");
69 return `[${this.state.opj[$1]}${$0}]`
70 });
71 console.log(str)
72 this.setState({
73 val:str
74 })
75 }
76
77 }
78 //粘贴触发的时间
79 paste(){
80 //--------
81 this.setState({
82 changeVal:this.state.val
83 })
84
85 }
86 }