2017-04-22 80 views
1

我有一個使用引導類的警報反應組件。反應警報組件關閉按鈕自我關閉

下面是部分代碼:

import React, { Component } from 'react'; 

class Alert extends Component { 
    render() { 
    return (
     <div> 
     <div className="alert alert-warning alert-dismissible" role="alert"> 
      <button type="button" className="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
      {this.props.text} 
     </div> 
     </div> 
    ); 
    } 
} 

export default Alert; 

它工作正常,但我的問題是...

如何獲得警報自我隱藏,當我點擊它的關閉按鈕?

回答

1

可以與國家內部做到這一點:

import React, { Component } from 'react'; 

class Alert extends Component { 

    constructor(props, context) { 
    super(props, context); 
    this.state = { 
     isActive: true, 
    } 
    } 

    hideAlert() { 
    this.setState({ 
     isActive: false, 
    }); 
    } 

    render() { 
    return (
     <div> 
     {this.state.isActive && <div className="alert alert-warning alert-dismissible" role="alert"> 
      <button type="button" className="close" data-dismiss="alert" aria-label="Close" onClick={() => this.hideAlert()}><span aria-hidden="true">&times;</span></button> 
      {this.props.text} 
     </div>} 
     </div> 
    ); 
    } 
} 
export default Alert;