繁体   English   中英

在 React 功能组件中使警报消息在 x 时间后消失

[英]Make a alert message disappear after x time in React functional component

我制作了一个过期组件,它允许其中的内容在 x 秒后消失。 它通过使用 state 和 setTimeout 工作。

import React, { useEffect, useState } from 'react';

function Expire(props)
{
    const [isVisible, setIsVisible] = useState(true);

    useEffect(() =>
    {
        setTimer(props.delay);
    }, []);


    const setTimer = (delay) =>
    {
        setTimeout(() => setIsVisible(false), delay);
    };

    return (
        isVisible
            ? <div>{props.children}</div>
            : <span />
    );
}

export default Expire;

我这样使用它:

<Expire delay="5000">
    <Alert type={alertMsgState} size="col-md-10" />
</Expire>

但我遇到的问题是,在 5 秒后消失一次后,当alertMsgState再次更改时 [例如。 再次提交表单,所以我想再次显示警报],消息不会重新呈现并在 5 秒后消失,就像它应该的那样。 在检查时,我只看到<span />元素。

请仅使用功能组件和挂钩回答。

您不会做任何会重新触发再次显示警报组件的操作。

例如,一种解决方案是使用 integer 密钥,当您想再次显示它时,请执行以下操作:

// inside parent
const [key, setKey] = useState(0);

// Say from a click handler when you again want to show your component, do:
let onClick=()=>{
  setKey(key+1);
}

//...

<Expire delay="5000" key={key}>
    <Alert type={alertMsgState} size="col-md-10" />
</Expire>

当不同渲染之间的 react 遇到具有不同键的组件时,它将卸载旧组件并再次安装它 - 因此您将获得所需的行为。

您可以做的一件事是将 useEffect 绑定到props.children ,因此无论何时更改,您都会重置消息,恢复可见性并再次开始超时:

function Expire(props)
{
    const [isVisible, setIsVisible] = useState(true);
    const [children, setChildren] = useState(props.children)

    useEffect(() =>
    {
        setChildren(props.children)
        setIsVisible(true)
        setTimer(props.delay);
    }, [props.children]);


    const setTimer = (delay) =>
    {
        setTimeout(() => setIsVisible(false), delay);
    };

    return (
        isVisible
            ? <div>{children}</div>
            : <span />
    );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM