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>