React 将任意 ReactNode 类型的节点在render函数外渲染到页面上

当一个 ReactNode 类型的节点,没有在 render 函数内时,如何渲染到页面上呢?

就需要借助 react-dom/client 中的 createRoot 函数,同时在不需要的时候销毁所有内容。

所以,就搞一个 hook 函数,函数加载的时候节点被 render 到页面上,函数卸载的时候卸载所有内容。同时增加当节点内容变化时更新 DOM 的功能。

tsx 复制代码
import React, { FC, useRef, useState, useEffect, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'


type useRenderDocumentProps = (renderNode: ReactNode) => void

const useRenderDocument: useRenderDocumentProps = (renderNode) => {

  const rootRef = useRef<HTMLDivElement | null>(null)
  const rootInstanceRef = useRef<Root | null>(null)

  const prevNode = useRef(renderNode)

  useEffect(() => {
    if (rootInstanceRef.current && prevNode.current !== renderNode) {
      rootInstanceRef.current.render(renderNode)
      prevNode.current = renderNode
    }
  }, [renderNode])

  useEffect(() => {

    if (!rootInstanceRef.current) {
      const root = document.createElement('div')
      root.className = 'render-root'
      document.body.appendChild(root)
      rootRef.current = root
      rootInstanceRef.current = createRoot(root)
      rootInstanceRef.current.render(renderNode)
    }
    return () => {
      console.log('销毁')
      if (rootRef.current) {
        rootRef.current.remove()
        rootRef.current = null
        rootInstanceRef.current?.unmount()
        rootInstanceRef.current = null
      }
    }
  }, [])
}

export default useRenderDocument
相关推荐
非优秀程序员5 小时前
第10章 千团出世|《互联网产品恩仇录》
前端
非优秀程序员5 小时前
第11章 小高在对面|《互联网产品恩仇录》
前端
非优秀程序员5 小时前
第14章 只剩美团|《互联网产品恩仇录》
前端
非优秀程序员5 小时前
第09章 老乡何必为难老乡|《互联网产品恩仇录》
前端
非优秀程序员5 小时前
第03章 三大门户,烽烟起于瀛海威|《互联网产品恩仇录》
前端
曦樂~9 小时前
【Web Development】02 CSS
前端·css
风骏时光牛马9 小时前
后端服务接口开发与数据逻辑处理
前端
东鹏特饮9 小时前
经典打砖块(Breakout)游戏
前端·css·css3
IT_陈寒10 小时前
Vite的HMR把我整不会了:一个生产环境的热更新坑
前端·人工智能·后端
Mh10 小时前
如何使用双缓冲优化视频切换
前端