基于React/JavaScript实现段落专属复制按钮功能
实现段落旁复制按钮的功能
要实现点击按钮复制对应段落内容的功能,你可以按以下步骤修改代码并实现复制逻辑:
1. 调整DOM结构,给每个段落搭配复制按钮
首先把列表项改成Flex布局,让文本和复制按钮在同一行显示,同时给标题复制按钮传入目标ID,方便关联文本:
<Stack spacing={3} ml={7} w="90%"> <Text fontSize={40} fontWeight="bold" mt="60px" mb="10px">Your Product Listing</Text> {/* 标题区域 */} <Flex direction="row" align="center"> <Text id='title' fontSize="32px" fontWeight="semibold" flex={1}> <Link color="#18A9FB" href='#'>Fleur de Sel</Link> - Premium Sea salt from Guerande France - <Link color="#18A9FB" href='#'>Flaky Sea Salt </Link> from the Celtic Sea - Salt Cork box - 3.5 Oz (100g) </Text> <Button variant='link' _hover={{ textDecoration: 'none' }} > <Icon as={AiOutlineReload} mr={2} ml={4} boxSize={8} /> </Button> <Button onClick={(e) => copyText(e, 'title')} variant='link' _hover={{ textDecoration: 'none' }}> <Icon as={MdContentCopy} mr={2} boxSize={8} /> </Button> </Flex> {/* 列表区域 */} <UnorderedList spacing={4}> {/* 列表项1 */} <ListItem display="flex" alignItems="center"> <Text flex={1}> AUTHENTIC HAND HARVESTED SALT: Tablissima french sea salt is carefully harvested by hand from the surface of salt ponds in the Guérande region of France. Centuries-old harvesting techniques are used to harvest a 100% natural salt that will provide a delicate taste to your food and make every bite delicious. </Text> <Button onClick={(e) => copyText(e)} variant='link' _hover={{ textDecoration: 'none' }}> <Icon as={MdContentCopy} mr={2} boxSize={8} /> </Button> </ListItem> {/* 列表项2 */} <ListItem display="flex" alignItems="center"> <Text flex={1}> ARTISANAL SEA SALT: Our Guérande Fleur de Sel is classified as IGP (Protected Geographical Indication), which guarantees you its origin, its natural production method and it's harvesting techniques. Our salt comes from a production with no pesticides, nor herbicides, no fossil nor carbon Energy. </Text> <Button onClick={(e) => copyText(e)} variant='link' _hover={{ textDecoration: 'none' }}> <Icon as={MdContentCopy} mr={2} boxSize={8} /> </Button> </ListItem> {/* 列表项3 */} <ListItem display="flex" alignItems="center"> <Text flex={1}> CAVIAR OF SALT: This finishing salt is loved by the best culinary professionals. Rich in minerals and lower in sodium than regular salt, it will give a delicate and subtle taste to any of your favourite dishes. </Text> <Button onClick={(e) => copyText(e)} variant='link' _hover={{ textDecoration: 'none' }}> <Icon as={MdContentCopy} mr={2} boxSize={8} /> </Button> </ListItem> {/* 列表项4 */} <ListItem display="flex" alignItems="center"> <Text flex={1}> MADE IN FRANCE: Our sea salt is harvested on the salt marshes of Guérande in France. Delicately picked from the surface of the water, it’s neither washed nor treated and drips naturally on our salt flats. Trusted by the best Chefs. </Text> <Button onClick={(e) => copyText(e)} variant='link' _hover={{ textDecoration: 'none' }}> <Icon as={MdContentCopy} mr={2} boxSize={8} /> </Button> </ListItem> </UnorderedList> </Stack>
2. 实现复制函数copyText
在组件中定义copyText函数,通过两种方式获取目标文本,同时加入浏览器兼容性处理:
const copyText = async (e, targetId) => { e.preventDefault(); let textToCopy = ''; if (targetId) { // 处理标题复制:通过ID获取文本内容 const titleElement = document.getElementById(targetId); textToCopy = titleElement.textContent.trim(); } else { // 处理列表项复制:通过DOM层级找到对应文本 const listItem = e.currentTarget.parentElement; const textElement = listItem.querySelector('Text'); textToCopy = textElement.textContent.trim(); } try { // 优先使用现代浏览器剪贴板API await navigator.clipboard.writeText(textToCopy); console.log('内容已复制到剪贴板'); // 可选:添加复制成功的视觉反馈,比如切换按钮图标 } catch (err) { console.error('剪贴板API调用失败,使用兼容模式:', err); // 兼容旧浏览器的 fallback 方案 const textArea = document.createElement('textarea'); textArea.value = textToCopy; document.body.appendChild(textArea); textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); console.log('兼容模式复制成功'); } };
关键说明
- 列表项设置
display="flex"和alignItems="center",保证文本与按钮垂直居中对齐 - 复制函数加入错误捕获,同时兼容不支持
navigator.clipboard的旧浏览器 - 可以根据需求扩展功能,比如复制成功后显示提示弹窗或切换按钮图标
内容的提问来源于stack exchange,提问作者Adugna Tadesse
相关产品推荐
相关产品推荐

