使用按钮可以很容易地进行通知。然而,我试图让它在道具通过时激活(真/假(。
基本上,用户点击这个标签,如果他们没有登录,它会弹出通知,告诉他们登录
然而,如果没有一个按钮,我就无法让它发挥作用。道具通过得很好,我可以进行console.log。条件返回。。。有些东西,但它就像一堆奇怪的字母,每次刷新都会发生变化。并且不会像通知一样弹出。它只是屏幕中间的模糊字母(因为{notice}位于表单上方(。
import React, {Component} from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
class Alerts extends Component {
constructor(props){
super(props)
this.state = {
alertLogin: ''
}
}
render() {
const notify = () => toast("Please login before adding a recipe!");
// tried to make a conditional to check if prop alertLogin is true or false
// then calls notify function if false
if (!this.props.alertLogin) {
console.log('alert props received', this.props.alertLogin)
return notify()
}
return (
<div>
{/* <button onClick={notify}>Notify !</button> */}
{notify}
<ToastContainer />
</div>
);
}
}
export default Alerts;
import React, { Component } from "react";
import "./styles.css";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
class Alerts extends Component {
constructor(props){
super(props)
this.state = {
alertLogin: ''
}
}
componentDidMount() {
// tried to make a conditional to check if prop alertLogin is true or false
// then calls notify function if false
if (!this.props.alertLogin) {
console.log("alert props received", this.props.alertLogin);
this.notify();
}
}
notify = () => toast("Please login before adding a recipe!");
render() {
return (
<div>
<button onClick={(e) => this.notify()}>Notify !</button>
<ToastContainer />
</div>
);
}
}
export default Alerts;
解决方案的Codepen
首先,将if语句与函数一起放入componentDidMount中原因我猜是停止渲染元素本身的渲染第二步,通过在呈现函数之前声明toast函数,使组件可以访问toast函数。希望我足够清楚