我正在处理react项目,当props(isNotificationOpen)为true时,我试图在div部分中使用react-toastify显示吐司。我尝试了一个类似波纹管的示例,但我不希望在按下按钮时触发吐司,我希望在将isNotificationOpen props设置为true时触发吐司,该如何实现?
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 />
)} ```
答案 0 :(得分:2)
使用组件生命周期功能来响应isNotificationOpen
道具更改以触发通知。
基于类的组件示例
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]);