在 React 中几秒钟后隐藏消息

Hide message after a few seconds in React

问题是关于在 5 秒后隐藏消息。

在下面的代码中,如果我单击“生成房间名称”按钮,它将在文本框中生成 url。我将使用“复制”按钮复制 url,然后将显示“已复制到剪贴板”消息。我想在 5 秒后隐藏该消息。请有人调查一下。

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>
    );
 }
}

谢谢

5000毫秒后清除copySuccess状态就足够了:

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

像这样修改您的 copyToClipboard 函数:

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

有关详细信息,请访问 here