当道具检查为真时,如何在 class 组件内使用 react-toastify 显示吐司
How to display toast using react-toastify inside class component when props check is true
我正在研究 React 项目,我试图在 div 部分中使用 react-toastify 显示吐司,当 props ( isNotificationOpen ) 为真时。我尝试了一个类似下面的示例,但我不希望在按下按钮时触发 toast,我希望在 isNotificationOpen 道具设置为 true 时触发 tost,我该如何实现?
const notify = () => toast("Wow so easy !");
render() {
return (
<div className="d-flex" style={{ margin: "25px" }}>
<div className="mr-auto p-2">
{this.props.isNotificationOpen ? (
<div>
<div>
<button onClick={notify}>Notify !</button>
<ToastContainer />
</div>
//Show toast here...
</div>
) : (
<p />
)} ```
使用组件生命周期函数来响应 isNotificationOpen
属性更改以触发通知。
Class-based 组件示例
notify = () => toast('Wow so easy!');
componentDidMount() {
const { isNotificationOpen } = this.props;
isNotificationOpen && this.notify();
}
componentDidUpdate(prevProps) {
const { isNotificationOpen } = this.props;
if (prevProps.isNotificationOpen !== isNotificationOpen) {
isNotificationOpen && this.notify();
}
}
功能组件示例
useEffect(() => {
props.isNotificationOpen && toast('Wow so easy!');
}, [props.isNotificationOpen]);
我正在研究 React 项目,我试图在 div 部分中使用 react-toastify 显示吐司,当 props ( isNotificationOpen ) 为真时。我尝试了一个类似下面的示例,但我不希望在按下按钮时触发 toast,我希望在 isNotificationOpen 道具设置为 true 时触发 tost,我该如何实现?
const notify = () => toast("Wow so easy !");
render() {
return (
<div className="d-flex" style={{ margin: "25px" }}>
<div className="mr-auto p-2">
{this.props.isNotificationOpen ? (
<div>
<div>
<button onClick={notify}>Notify !</button>
<ToastContainer />
</div>
//Show toast here...
</div>
) : (
<p />
)} ```
使用组件生命周期函数来响应 isNotificationOpen
属性更改以触发通知。
Class-based 组件示例
notify = () => toast('Wow so easy!');
componentDidMount() {
const { isNotificationOpen } = this.props;
isNotificationOpen && this.notify();
}
componentDidUpdate(prevProps) {
const { isNotificationOpen } = this.props;
if (prevProps.isNotificationOpen !== isNotificationOpen) {
isNotificationOpen && this.notify();
}
}
功能组件示例
useEffect(() => {
props.isNotificationOpen && toast('Wow so easy!');
}, [props.isNotificationOpen]);