Javascript 反应警报组件关闭按钮自动关闭
我有一个alert react组件,它使用引导类 以下是组件代码:Javascript 反应警报组件关闭按钮自动关闭,javascript,reactjs,Javascript,Reactjs,我有一个alert react组件,它使用引导类 以下是组件代码: import React, { Component } from 'react'; class Alert extends Component { render() { return ( <div> <div className="alert alert-warning alert-dismissible" role="alert"> <
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}来自'React';
类警报扩展组件{
render(){
返回(
&时代;
{this.props.text}
);
}
}
导出默认警报;
这很好,但我的问题是
单击其中的“关闭”按钮时,如何使警报自动隐藏?您可以使用以下状态在内部执行此操作:
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() {
if (this.state.isActive) {
return (
<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>
);
}
return <div/>
}
}
export default Alert;
import React,{Component}来自'React';
类警报扩展组件{
构造函数(道具、上下文){
超级(道具、背景);
此.state={
是的,
}
}
希德勒特(){
这是我的国家({
I:错,
});
}
render(){
if(this.state.isActive){
返回(
this.hideAlert()}
>
&时代;
{this.props.text}
);
}
返回
}
}
导出默认警报;
我知道这个问题不是今年提出的,但我发现,可能会有更多的人在寻找它
所以,我把它作为一个带有钩子的功能组件来做。我仍然是这个领域的初学者,所以请随意为我指出一些东西,这样我们就可以一起学习:)
编辑:在这里你可以切换弹出窗口,如果你只想关闭它,你可以使用setShowPopup功能不切换,而是将其设置为false-无论你需要什么
这是我的密码:
import React from 'react';
function Alert() {
const [showPopup, setShowPopup] = React.useState(false);
const toggleShowInfoPopup = () => {
setShowPopup(!showPopup);
};
return (
<div>
<div className="alert alert-warning alert-dismissible" role="alert">
<button
type="button"
className="close"
data-dismiss="alert"
aria-label="Close"
onClick={toggleShowInfoPopup}
>
<span aria-hidden="true">×</span>
</button>
{this.props.text}
</div>
</div>
);
}
export default Alert;
从“React”导入React;
函数警报(){
const[showPopup,setShowPopup]=React.useState(false);
const toggleShowInfoPopup=()=>{
设置showPopup(!showPopup);
};
返回(
&时代;
{this.props.text}
);
}
导出默认警报;
使用状态来操纵显示行为。setTimeout函数以更改状态存在键入错误OnClick={toggleShowPopup}
应该是OnClick={toggleShowInfoPopup}
您还应该基于showPopup
的值进行渲染,否则切换将不起作用