剪贴板功能的实现

  • 利用利用的插件包 clipboard-polyfill
import React, {
      Component } from 'react'

import clipboard from "clipboard-polyfill"
import {
     Button} from "antd"

export default class Main extends Component {
     
    constructor(props){
     
        super(props);
        this.state={
     
            opj:{
     
                "param.code.name":"姓名",
                "param.codexname":"昵称",
                "param.code.age":"年龄",
                "param.code.gender":"性别",
                "param.code.hobby":"爱好",
            },
            val:"大家好这是新来的同学,叫 ,也可以叫,今年了,喜欢,也喜欢",
            changeVal:""
        }
    }
    render() {
     
        //console.log(Object.entries(this.state))
        return (
            <div>
                <div className="top">
                    {
     Object.entries(this.state.opj).map((item,index)=>{
     
                        return <Button  className="btn" key={
     index} onClick={
     this.copy.bind(this,index,item)}>{
     item[1]}</Button>
                    })}
                </div>
                <textarea name="" id="text" ref="text" onPaste={
     this.paste.bind(this)} cols="30" rows="10" value={
     this.state.val} onChange={
     (e)=>{
     
                    this.setState({
     
                        val:e.target.value
                    })
                }} />
                <button onClick={
     this.del.bind(this)}>去除value</button>
                <button onClick={
     this.add.bind(this)}>补充value</button>
            </div>
        )
    }
    copy(index,item){
     
        //document.execCommand("Copy"); // 执行浏览器复制命令
        // let btn=document.querySelectorAll(".btn")[index]
        // btn.value=`[${item[1]}(${item[0]})]`
        // btn.select()
        // console.log(document.execCommand("Copy"))
        // btn.value=item[1]
        
        let text=`[${
     item[1]}(${
     item[0]})]`;
        //将文字复制到剪贴板
        clipboard.writeText(text)
        //console.log(text);
    }
    del(){
     
        let str=this.state.val;
        str=str.replace("]","")
        let res=/\[.*?\(/g;
        str=str.replace(res,"(")
        //console.log(str);
        this.setState({
     
            val:str
        })
    }
    add(){
     
        let str=this.state.val;
            if(str.indexOf("]")<0){
     
                console.log(111)
                str=str.replace(/\((.+?)\)/g,  ($0,$1,$2)=> {
     
                    console.log($0,$1,$2,"============");
                    return `[${
     this.state.opj[$1]}${
     $0}]`
                  });
                  console.log(str)
                  this.setState({
     
                    val:str
                  })
            }
       
    }
    //粘贴触发的时间
    paste(){
     
        //--------
        this.setState({
     
            changeVal:this.state.val
        })
        
    }
}

你可能感兴趣的:(React案例)