react & vue & angular

582. 【前端】React 组件调试小技巧

2023-02-15  本文已影响0人  七镜

一般我们在调试单个React组件时,借助于热更新,我们改改代码可以在浏览器实时看到更新,但当项目比较大的时候,我们调试的页面在整个应用中的路由层级比较深,就会导致:每一次咱们修改完一个地方的代码,浏览器自动刷新到了首页,并进入修改的页面,才能看到更新之后的变化。

介于此,这篇分享一个前端调试React组件的方法。

一、使用 createPortal 构建测试组件

scss代码:

.test-container {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background-color: white;
  z-index: 99999999999999999999999999999;
  top: 0;
}

tsx代码:

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'

使用示例如下:

<TestContainer element={<IMarkdown content={content}/>} />

总结:作为一个开发,如果开发过程中有件事一直在重复做,那么就应该想解决方案,解决这个问题。比如重复的代码,就可以封装起来。比如重复的文件复制粘贴,在windows下可以写bat脚本,在linux下可以写shell脚本;比如每天都要执行测试用例的执行,就可以集成到CI/CD(continuous integration/continuous deloyment/delivery)中。

上一篇 下一篇

猜你喜欢

热点阅读