剪貼板功能的實現

  • 利用利用的插件包 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
        })
        
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章