如何解决React js中的React Bootstrap SweetAlert无法正常工作
我正在尝试使用sweetalert
创建一个注销按钮。我创建了一个注销功能,该功能在没有sweetalert
的情况下也可以正常工作。但是,当我添加sweetalert
按钮时,它将停止工作。
这是我的代码。请帮助我...
import React,{Component } from 'react';
import SweetAlert from 'react-bootstrap-sweetalert';
class Hero extends Component {
constructor(props) {
super(props);
this.state = {
alert: null
};
}
showAlert = () => (
this.setState = ({
alert: (
<SweetAlert
title="Here's a message!"
onConfirm={this.props.handleLogout}
onCancel={this.onCancel}
showCancel={true}
focusCancelBtn={true}
/>
)
})
);
render(){
return (
<section className = "hero">
<nav>
<h2>Book Exchange</h2>
<button onClick = {() => this.showAlert()}>Logout</button>
</nav>
</section>
);
}
};
export default Hero;
下面是我的handleLogout
函数,它在没有sweetalert
的情况下可以正常工作。我正在使用Firebase进行身份验证。
const handleLogout = () => {
fire.auth().signOut()
};
解决方法
请注意,不要为setState
分配新状态,而应将其作为函数执行。
然后,您可以尝试按条件执行警报,如下所示:
import React,{Component } from 'react';
import SweetAlert from 'react-bootstrap-sweetalert';
class Hero extends Component {
constructor(props) {
super(props);
this.state = {
alert: false,};
}
showAlert = () => {
this.setState({
alert: true,})
};
render(){
return (
<>
<section className = "hero">
<nav>
<h2>Book Exchange</h2>
<button onClick = {this.showAlert}>Logout</button>
</nav>
</section>
{
this.state.alert && <SweetAlert
title="Here's a message!"
onConfirm={this.props.handleLogout}
onCancel={this.onCancel}
showCancel={true}
focusCancelBtn={true}
/>
}
</>
);
}
};
export default Hero;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。