React 实现复制功能

React 实现复制功能

以下都是Antd4.x的写法

//hook写法----------通过useRef
import React, { useRef } from 'react';
import styles from './index.less';
import { Input, Button } from 'antd';
const Export = (props) => {
  const linkRef = useRef();
  //复制链接
  const copyLink = () => {
    linkRef.current.select();  //全选
    document.execCommand('copy', true);  //复制
  };

  return (
    <div className={styles.exportModal}>
      <p style={{ textAlign: 'center', color: '#333', fontSize: 16 }}>请复制链接到浏览器打开</p>
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <Input
          value={props.url}
          ref={linkRef}
          style={{ width: 200, marginRight: 8 }}
          onSelect={(e) => {
            console.log('object', e);
          }}
        />
        <Button type="primary" onClick={copyLink}>
          复制链接
        </Button>
      </div>
    </div>
  );
};
export default Export;

//class写法
import React, { Component } from 'react';
import { Input, Button } from 'antd';
class List extends Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
    };
  }
  
  //复制链接
  copyLink = () => {
    this.linkInput.select();  //全选
    document.execCommand('copy', true);  //复制
  };

<div className={styles.spread}>
	<div className={styles.title}>
		<span style={{ fontSize: 16, color: '#000' }}>
			推广链接
			<span style={{ fontSize: 14, color: '#999' }}>(复制链接到店铺装修推广)</span>
		</span>
	</div>
	<div className={styles.link}>
		<Input value={link.linkUrl} readOnly ref={(link) => (this.linkInput = link)} />
		<Button type="primary" onClick={this.copyLink}> 复制链接 </Button>
	</div>
</div>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值