一般我们在调试单个React组件时,借助于热更新,我们改改代码可以在浏览器实时看到更新,但当项目比较大的时候,我们调试的页面在整个应用中的路由层级比较深,就会导致:每一次咱们修改完一个地方的代码,浏览器自动刷新到了首页,并进入修改的页面,才能看到更新之后的变化。
介于此,这篇分享一个前端调试React组件的方法。
.test-container {
position: fixed;
width: 100vw;
height: 100vh;
background-color: white;
z-index: 99999999999999999999999999999;
top: 0;
}
import React, {
FC,
useState,
useEffect,
ReactNode
} from "react";
import './test-container.scss'
import {createPortal} from "react-dom";
interface TestContainerProps {
element: ReactNode;
}
export const TestContainer: FC<TestContainerProps> = (props) => {
const [isReady, setIsReady] = useState<boolean>(false)
useEffect(() => {
setIsReady(true)
}, [])
if (!isReady) return null
return createPortal(<article className={"test-container"}>
{props.element}
</article>, document.body)
}
TestContainer.defaultProps = {}
export {TestContainer as default} from './test-container'
ReactNode
传进来就可以了。<TestContainer element={<IMarkdown content={content}/>} />
IMarkdown
是我需要测试的组件(对react-markdown
的封装)。