我們的照片要給使用者分享和下載的功能,雖然說可以拷貝瀏覽器的網址,但是在手機上要拷貝文字實在是不方便,我們可以做一個按鈕讓使用者按下去就將網址複製到剪貼簿裡。React-Toolbox有提供 dialog 的UI元件,我們可以在對話框裡加入複製網址的按鈕。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {Dialog} from 'react-toolbox';
import appStyle from './app.css';
// IE polyfill for .remove()
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('remove')) {
return;
}
Object.defineProperty(item, 'remove', {
configurable: true,
enumerable: true,
writable: true,
value: function remove() {
this.parentNode.removeChild(this);
}
});
});
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
class ShareDialog extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false,
copied: false
};
this.actions = [
{ label: '取消', onClick: props.handleShare },
{ label: '複製連結', onClick: () => this.handleCopy() }
];
this.newAction = [
{ label: '好', onClick: props.handleShare }
];
if(props.type === 'album') {
this.type = '相簿';
} else if(props.type === 'photo') {
this.type = '照片';
}
this.handleCopy = this.handleCopy.bind(this);
}
componentWillReceiveProps(nextProps) {
if(nextProps.active) {
this.setState({
copied: false
});
}
this.setState({
active: nextProps.active
});
}
handleCopy() {
// run copy to clipboard function
let textField = document.createElement('textarea');
textField.innerText = this.props.link;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
textField.remove();
// text is copied
this.setState({
copied: true
});
}
render() {
return (
<div>
<Dialog
title = {`分享${this.type}給別人`}
active = {this.state.active}
actions = { this.state.copied ? this.newAction : this.actions}
onOverlayClick = {this.props.handleShare}
onEscKeyDown = {this.props.handleShare}
>
<p className={appStyle['dont-break-out']}>{this.props.link}</p>
{ this.state.copied && <p style={{color:'#00695C', marginTop:'16px', fontWeight:'500'}}>此連結已複製到剪貼簿!</p> }
</Dialog>
</div>
);
}
}
export default ShareDialog;