在项目中使用到复制粘贴功能,虽然网上有不少大牛封装了不少的插件,可是仍是想不去使用插件,就像本身来实现这个功能。css
初步想法: 1. 获取到须要复制的内容,这里我能够将须要复制的内容放在input或者textarea的value中,而后使用input的select()方法来获取到值; 2. 获取到值了,那我下一步就是复制了,document.execCommand()方法能够操做不少功能,这里我能够使用他的copy复制选中的文字到粘贴板的功能; 3. 复制功能实现了,可是这个input或者textarea不是我页面布局中所须要的,那我能够将input或者textarea设置成透明的; 代码实现: 1. js: import React, {PureComponent} from 'react'; import PropTypes from 'prop-types'; import './index.less' class CopyClip extends PureComponent { static propTypes = { text: PropTypes.any, //文字内容 ID: PropTypes.string }; static defaultProps = { ID: 'copy-clip-textarea', }; constructor(props) { super(props); this.state = {} } componentWillMount() { const {text} = this.props; this.setState({ text }) } componentWillReceiveProps(nextProps) { const {text} = nextProps; this.setState({ text }) } handleCopy = () => { let {ID} = this.props; let range, selection; let input = document.getElementById(ID); input.select(); // 获取到须要复制的内容 if (input.value && ((typeof input.select) == 'function')) { range = document.createRange(); // 建立range对象 selection = document.getSelection(); // 返回一个Selection 对象,表示用户选择的文本范围或光标的当前位置。 range.selectNode(input); selection.addRange(range); input.setSelectionRange(0, input.value.length); // 为当前元素内的文本设置备选中范围 let successful = document.execCommand('copy'); // 使用document.execCommand()方法, copy指令复制选中的文字到粘贴板的功能 if (!successful) { this.props.onCopy(false); window.clipboardData.setData('text', this.state.text); // 解决部分浏览器复制以后没有粘贴到粘贴板,使用浏览器自带的粘贴板 } else { this.props.onCopy(true) } } else { this.props.onCopy(false) } }; render() { const {text} = this.state; return ( <div className="common-copy-clip" onClick={() => this.handleCopy()}> <textarea readOnly="readonly" id={this.props.ID} value={text}></textarea> {this.props.children} </div> ) } } export default CopyClip 2. css .common-copy-clip { position: relative; textarea { position: absolute; top: 0; opacity: 0; }
}react