import React, {useCallback, useLayoutEffect, useRef} from "react"; import {findDOMNode} from "react-dom"; export interface iKeepAliveCacheItemWrapperProps { children: any, active: boolean } export const KeepAliveCacheItemWrapper: React.FC = (props) => { /** * 销毁前将dom放回去,避免react-dom渲染异常 * 这里要比 startText.domRef更新前执行,不然当前组件销毁的时候拿不到startText.domRef.current * startText.domRef在useLayoutEffect清除副作用的时候清理掉了startText.domRef.current * 放回去之前,先把display设置为none,避免放回去的一瞬间出现还原内容的现象 * @author 韦胜健 * @date 2023.6.3 18:31 */ useLayoutEffect(() => { return () => { isDestroy.current = true; removeElements.current.forEach(el => { if ('style' in el) { ;(el.style as any).display = 'none'; } }); show(); }; }, []); /*对start text节点的引用*/ const startText = useTextRef(); /*对end text节点的引用*/ const endText = useTextRef(); /*目前移除的dom*/ const removeElements = useRef([] as Element[]); /*当前是否已经激活*/ const currentActive = useRef(true); /*当前组件是否已经销毁*/ const isDestroy = useRef(false); /** * 还原显示dom节点 * @author 韦胜健 * @date 2023.6.3 18:30 */ const show = useCallback(() => { try { currentActive.current = true; const parentNode = startText.domRef.current!.parentNode!; removeElements.current.forEach(el => { parentNode.insertBefore(el, endText.domRef.current!); }); } catch (e) { console.error(e); } }, []); /** * 隐藏dom节点 * @author 韦胜健 * @date 2023.6.3 18:30 */ const hide = useCallback(() => { currentActive.current = false; let elementList = [] as Element[]; const startTextDom = startText.domRef.current; const endTextDom = endText.domRef.current; let temp: ChildNode | null = startTextDom; while (!!temp && temp !== endTextDom) { temp = temp.nextSibling; if (!!temp && temp !== endTextDom) { elementList.push(temp as any); } } elementList.forEach(el => {el.parentNode!.removeChild(el);}); removeElements.current = elementList; }, []); useLayoutEffect(() => { if (isDestroy.current) {return;} if (currentActive.current && !props.active) { hide(); } else if (!currentActive.current && props.active) { show(); } }); return <> {props.children} ; }; class EmptyText extends React.Component { render() { /*这个空格失是必须得*/ return (' '); } } function useTextRef() { const componentRef = useRef(null as any); const domRef = useRef(null as null | Text); useLayoutEffect(() => { domRef.current = findDOMNode(componentRef.current) as Text; return () => {domRef.current = null;}; }, []); return { componentRef, domRef }; }