title: copyCode slug: copyCode date: 2024-8-21 id: 10 tags: - js 复制代码实现很简单,就是加了icon和css,最后调用navigator的剪贴板对象的writeText方法icon是lucide-reactcss主要用于定位传进来的对象需要为code源码,没有tag,在传值的时候记得处理copyCode.js"use client" import {Copy,CopyCheck} from "lucide-react"; import {useState} from "react"; const CopyCode = ({code}) => { const copyCode = () => { navigator.clipboard.writeText(code) setIsCopy(true) setTimeout(() => { setIsCopy(false) }, 500) } const [isCopy, setIsCopy] = useState(false) return ( <div> {isCopy ? <CopyCheck size={20} style={{color:'green'}}/> : <Copy size={20} onClick={copyCode}/> } </div> ); } export default CopyCodeusage样式按需定义if (domNode.name === 'pre' && domNode.children[0]?.name === 'code') { const codeBlock = domNode.children[0]; const codeContent = codeBlock.children[0].data; return ( <div className={styles.codeBlock}> <span className={styles.copy}> <CopyCode code={codeContent}/> </span> </div> ) }