反应警报组件关闭按钮自我关闭
问题描述:
我有一个使用引导类的警报反应组件。反应警报组件关闭按钮自我关闭
下面是部分代码:
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">×</span></button>
{this.props.text}
</div>
</div>
);
}
}
export default Alert;
它工作正常,但我的问题是...
如何获得警报自我隐藏,当我点击它的关闭按钮?
答
可以与国家内部做到这一点:
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">×</span></button>
{this.props.text}
</div>}
</div>
);
}
}
export default Alert;