我有onclick事件的警报。但是我希望警报持续两秒钟,并在2秒后自动关闭。如何在reactJS中设置警报超时时间?


const handleHide1 = () => this.setState({ show1: false });
const handleShow1 = () => this.setState({ show1: true });

return(
<div>
<Alert show={this.state.show1} variant="success" style={{marginTop:'2%'}} onHide={this.handleHide1} >
<Alert.Heading closeButton>Order Accepted
<button type="button" class="close" onClick={handleHide1} aria-label="Close">
<span aria-hidden="true">&times;</span></button>
</Alert.Heading>
<p>Thank you for Accepting Order. We will inform the customer</p>
</Alert>

<Button variant="outline-success" onClick={()=>{handleShow1}>Accept</Button>

最佳答案

像这样吗:

const handleShow1 = () => {
  this.setState({
     show1: true
  })

  setTimeout(() => {
     this.setState({
         show1: false
     })
  }, 2000)


}

另外,这是我为您准备的一个沙盒,可让您对此有所了解:
https://codesandbox.io/s/2w03nvvjnp

09-18 20:03