简体   繁体   English

在 React 中几秒钟后隐藏消息

[英]Hide message after a few seconds in React

The question is about hiding a message after 5 seconds.问题是关于在 5 秒后隐藏消息。

In the code below, if I click on the Generate Room Name button, it will generate the url in the textbox.在下面的代码中,如果我单击生成房间名称按钮,它将在文本框中生成 url。 I will be copying that url using the Copy button and a "Copied to clipboard" message will be displayed.我将使用“复制”按钮复制 url,然后将显示“已复制到剪贴板”消息。 I want to hide that message after 5 seconds.我想在 5 秒后隐藏该消息。 Please someone look into it.请有人调查一下。

import React from 'react';
import FlashMessage from 'react-flash-message'
import Iframe from 'react-iframe';
 export default class CustomView extends React.Component {
 constructor(props) {
 super(props);
  this.state = {
  roomname: '',
  copySuccess: '',
  enablebutton: true
  }
}
 makeid() {
let r = (Math.random() + 1).toString(36).substring(7);
console.log("random", r);
this.setState({
  roomname: r,
  enablebutton: false
})
}
copyToClipboard = (e) => {
this.textArea.select();
document.execCommand('copy');
e.target.focus();
this.setState({ copySuccess: 'Copied!' });
};
render() {
return (
  <div>
    <button onClick={this.makeid.bind(this)}> Generate RoomName</button>
          <div style={{ display: "flex", marginLeft: '19%', marginTop: '-2%' }}>
         <form disabled={this.state.enablebutton}>
         <textarea style={{
          width: "457px",
          height: "15px"
        }} disabled={this.state.enablebutton}
          ref={(textarea) => this.textArea = textarea}
          value={`https://xxxxxxxxx.azurewebsites.net/?roomname=${this.state.roomname}`}/>
      </form>
      {
     document.queryCommandSupported('copy') &&
        <div disabled={this.state.enablebutton}>
          <button onClick={this.copyToClipboard}>Copy</button>
            <p style={{ color: "red" }}> {this.state.copySuccess}</p>
        </div>
      }
        </div>

  </div>
    );
 }
}

Thanks谢谢

It's enough to clear the copySuccess state after 5000 ms:在 5000 毫秒后清除copySuccess state 就足够了:

copyToClipboard = (e) => {
this.textArea.select();
document.execCommand('copy');
e.target.focus();
this.setState({ copySuccess: 'Copied!' }, () => setTimeout( () => this.setState({ copySuccess: '' }) ,5000));
};

Modify your copyToClipboard function like this:像这样修改您的copyToClipboard function :

copyToClipboard = (e) => {
this.textArea.select();
document.execCommand('copy');
e.target.focus();
this.setState({ copySuccess: 'Copied!' });
setTimeout(() => {
    this.setState({ copySuccess: '' });
  }, 5000);
};

for more info visit here欲了解更多信息,请访问此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM