猿问

React 功能组件 - 如何从内部删除组件?

我有一个基于用户操作显示的警报组件:


export default function Alert({text, type, hideable = true, stick = true}) {

    const [hide, setHide] = useState(false);

    const [id, setId] = useState(makeId(5));

    const alertEl = (

        <div key={id} id={id} className={"fade alert alert-" + type} role="alert">

            {hideable

                ? <span className="icon-close close" onClick={e => fadeOut()}> </span>

                : ''

            }

            {text}

        </div>

    );


    function fadeOut() {

        document.getElementById(id).classList.add('fade-out');

        window.setTimeout(() => {

            setHide(true);

        }, 500)

    }


    useEffect(() => {

        if (!stick) {

            window.setTimeout(() => fadeOut(), 3000);

        }

    }, [])


    if (hide) return '';

    return alertEl;

}

它是这样使用的:


setResponseAlert(<Alert 

    text="Please check the field errors and try again." 

    type="danger" stick={false} hideable={false}

/>)

问题是实例化 Alert 组件仍然返回旧组件。Alert 组件消失后如何实现移除?


SMILET
浏览 125回答 1
1回答

小唯快跑啊

向下传递,setResponseAlert以便可以使用null或undefined代替使用hide状态来调用它。此外,而不是使用getElementById,因为这是 React,你应该以某种方式将 fade 类放入状态:export default function Alert({text, type, setResponseAlert, hideable = true, stick = true}) {&nbsp; &nbsp; const [className, setClassName] = useState("fade alert alert-" + type);&nbsp; &nbsp; function fadeOut() {&nbsp; &nbsp; &nbsp; &nbsp; setClassName(className + ' fade-out');&nbsp; &nbsp; &nbsp; &nbsp; window.setTimeout(() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setResponseAlert(null);&nbsp; &nbsp; &nbsp; &nbsp; }, 500)&nbsp; &nbsp; }&nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; &nbsp; if (!stick) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.setTimeout(fadeOut, 3000);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }, [])&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div role="alert" className={className}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {hideable&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? <span className="icon-close close" onClick={e => fadeOut()}> </span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : ''&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {text}&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答