在項目中使用到複製粘貼功能,雖然網上有不少大牛封裝了不少的插件,可是仍是想不去使用插件,就像本身來實現這個功能。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