单击reactjs中的复制按钮时如何创建“复制到剪贴板”的工具提示

时间:2018-07-11 11:39:04

标签: reactjs

我试图在单击复制按钮时创建“复制到剪贴板”的工具提示。 下面是代码,

constructor(props) {
    super(props)
    this.state = {
        tool_tip_content: '',
    };
}

click = () => {
    this.input_ref.current.select();
    document.execCommand('copy');
    this.input_ref.current.blur();
    this.setState({ tool_tip_content: 'Copied to clipboard'});
};

<input readOnly ref={this.input_ref} value="hello"/>
<button onClick={this.click}>COPY</button>
    <span style={tooltipStyle}>Copied to Clipboard </span>

我尝试过的如下,

constructor(props) {
    super(props)
    this.state = { on_copy_link_click: false }
}

click = () => {
    this.setState({ on_copy_link_click: true);
    this.input_ref.current.select();
    document.execCommand('copy');
};
mouse_out = () => {
     this.setState({ tool_tip_content: ''});
};
<div className="tooltip">
    <input readOnly ref={this.input_ref} value="hello"/>
    <button onClick={this.click} onMouseOut={this.mouse_out}>COPY</button>
        <span className="tooltiptext">{this.state.tool_tip_content} </span>
</div>

copylink工具提示的样式如下,

.tooltip {
    position: relative;
    display: inline-block;
}
.tooltip .tooltiptext {
    visibility: hidden;
    width: 140px;
    background-color: #555;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    padding: 5px;
    position: absolute;
    z-index: 1;
    bottom: 150%;
    left: 50%;
    margin-left: -75px;
    opacity: 0;
    transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -5px;
    border-width: 5px;
    border-style: solid;
    border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
    visibility: visible;
    opacity: 1;
}

以上代码的工作原理如下所述, 1.将鼠标悬停在copylink按钮上时,将显示空白内容的工具提示 2.单击带有内容“已复制到剪贴板的复制链接”按钮工具提示时 3.在鼠标移出时不显示工具提示

预期结果: 仅在单击复制链接按钮时,我希望工具提示显示为“复制到剪贴板”的内容。在mouserover和mouseout工具提示上不应该显示。

有人可以帮我吗。谢谢。

2 个答案:

答案 0 :(得分:1)

最好使用react-tooltip之类的任何库,这使您的工作变得容易。

答案 1 :(得分:0)

在这种情况下,您可以使用条件渲染...

   {this.state.tool_tip_content.length>0 && <span className="tooltiptext">{this.state.tool_tip_content} </span> }