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
相关推荐
别惊醒渔人1 小时前
Vue3 Diff 优化:最长递增子序列 LIS
前端·javascript·vue.js
颜酱2 小时前
07 | 把字段与指标同步到 Qdrant(生成阶段)
前端·人工智能·后端
用户059540174462 小时前
把AI长期记忆测试从手动验证换成pytest,2天揪出11个隐藏Bug
前端·css
lichenyang4533 小时前
从 Vite 空项目到 AIGC 图片工作台:我如何打通生图、任务轮询、生成库与 Canvas 动态特效
前端·人工智能
泡沫冰@3 小时前
上章节中文件的讲解
前端·网络·nginx
进击的丸子3 小时前
APP人脸识别增值版Harmony Demo实操与关键代码解析
前端·程序员·harmonyos
a1117764 小时前
唯美花朵风格的黑胶唱片音乐播放器
前端·css·css3
Hilaku4 小时前
工作 5 年后,决定你薪资上限的究竟是什么?
前端·javascript·程序员
爱分享的程序猿-Clark4 小时前
【前端分享】vue3 有 keep-alive属性吗?
前端
Revolution614 小时前
页面更新后为什么出现 Loading chunk failed:旧页面如何请求了已删除的构建产物
前端·面试·前端工程化