[英]Showing notification outside the render, in the function in React
我是新手,我创建了一个登录页面,我想使用通知来显示错误的用户/密码等错误...我创建了一个通知组件这是我的通知组件
import React from 'react';
import Style from './notifications.css';
import { Container } from 'react-bootstrap';
class Notifications extends React.Component{
constructor(props){
super(props);
this.state={
top: -100,
errorText: '',
};
}
onShow = () => {
}
showNotification= () => {
this.setState({
top: 16,
}, () => {
setTimeout(() => {
this.setState({
top: -100,
});
}, 3000);
});
}
render(){
return(
<React.Fragment>
<Container top={this.state.top}>{this.state.errorText}</Container>
</React.Fragment>
);
}
}
export default Notifications;
我想在我的 app.js 中使用这个组件,这是我的 app.js
import React from 'react';
import Notifications from './Notifications/notifications';
showNatify = (errorText) => {
<Notifications errorText={errorText} ></Notifications>
submitFunAjax = () => {
if (this.checkForSubmit() === true) {
// Some Codes
}
Tools.Fetch(this, "Authentication.asmx/LoginToSystem", myParams, function (sender, response) {
if (response[0] === "true") {
//use my component for success
}
else if (response[0] === "false") {
// use my component for danger
}
})
}
}
我建议你使用React Toastify package。 这非常易于使用,您可以根据需要轻松配置。
要安装,运行:
npm install --save react-toastify
这是一个如何使用它的简单演示。
import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
function App(){
const notify = () => toast("Wow so easy !");
return (
<div>
<button onClick={notify}>Notify !</button>
<ToastContainer />
</div>
);
}
这是一个现场演示。 希望这可以帮助!! 编码快乐!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.