实现自己的mini-React 1(手摸手系列)

写在开头,本系列篇幅较长包含大量代码及思考逻辑,主要实现涉及React中的:

  • Function Component
  • useEffect
  • useState
  • 点击事件处理及props绑定
  • 任务调度器
  • Fiber架构(树结构到链表结构转换)

文章会从main.jsx结合jsx处理后的dom树及源码带入react的大概实现逻辑,先上代码链接(后续会更新优化,方便阅读),文章产出源自@阿崔cxr的mini-react活动课程。

Step 1 项目搭建

本文使用vite搭建的js空项目,后续可以直接上jsx语法,结合react项目的入口文件开始反推;

如上图所示,关键代码在最后一行,意在通过ReactDOM的createRoot传入一个根节点,返回一个render函数处理App组件;可以猜想到是App组件在通过jsx转换后给到render函数渲染vDom,最后挂载到根节点上。

拆分任务

  • 先上js语法,从最基础的dom创建、vDom生成
  • 修改函数名及层级结构,对齐react
js 复制代码
// 创建 vdom

function createTextNode(text){
    return {
        type: 'TEXT_ELEMENT',
        props: {
            nodeValue: text,
            children: []
        }
    }
}
function createElement(type, props, ...children){
    return {
        type,
        props: {
            ...props,
            children: children.map(el => typeof el === 'string'?createTextNode(el):el)
        }
    }
}
/**
 * 
 * @param {创建元素} el 
 * @param {容器元素} container 
 */
function myRender(el,container) {
    // 创建元素
    const dom = el.type === 'TEXT_ELEMENT' 
    ? document.createTextNode('')
    : document.createElement(el.type)
    // 处理props
    Object.keys(el.props).map(key =>{
        if(key !== 'children'){
            // 属性赋值
            dom[key] = el['props'][key]
        }
    })
        // 处理children
        el['props']['children'].map(child =>{
            // 插入父节点
            myRender(child, dom)
        })
    container.appendChild(dom)
}

const root = document.querySelector('#root')
// root.appendChild(dom)

// ?1 优化
const App = createElement('div',{id:'app'},'test 03')
// myRender(App,root)

const ReactDOM = {
    createRoot(container){
        return {
            render(el){
                myRender(el,container)
            }
        }
    }
}

ReactDOM.createRoot(root).render(App)

vDom创建与函数名对齐

根据官网的const element = createElement(type, props, ...children),我们知道创建dom需要传递的数据及类型,而后区分节点类型是文本节点还是其他dom节点。

关于vDom的数据结构,其中props嵌套children,可以拉平也可以嵌套,嵌套是为了和react对齐。

文件层级划分及拆分React.js、ReactDom.js

拆分结果ReactDom.js图:

App.js 代码结构:

js 复制代码
import React from './core/React.js';
const App = createElement('div',{id:'app'},'test 03')
export default App

main.js 的代码结构图:

React.js 代码结构,修改myRender=>render对齐react:

js 复制代码
/ 创建 vdom

function createTextNode(text){
    return {
        type: 'TEXT_ELEMENT',
        props: {
            nodeValue: text,
            children: []
        }
    }
}
function createElement(type, props, ...children){
    return {
        type,
        props: {
            ...props,
            children: children.map(el => typeof el === 'string'?createTextNode(el):el)
        }
    }
}
/**
 * 
 * @param {创建元素} el 
 * @param {容器元素} container 
 */
function render(el,container) {
    // 创建元素
    const dom = el.type === 'TEXT_ELEMENT' 
    ? document.createTextNode('')
    : document.createElement(el.type)
    // 处理props
    Object.keys(el.props).map(key =>{
        if(key !== 'children'){
            // 属性赋值
            dom[key] = el['props'][key]
        }
    })
        // 处理children
        el['props']['children'].map(child =>{
            // 插入父节点
            myRender(child, dom)
        })
    container.appendChild(dom)
}
const React = {
 render,
 createElement
}

到此第一步的工作已经完成,mini-react的形有了,下一步丰富内在。

相关推荐
Ai-_Man3 分钟前
我需要批量导出Poe左边栏所有对话,而不是一条具体的对话内容,你们AI导出鸭可以吗?
开发语言·前端·javascript·人工智能·小程序
java1234_小锋4 分钟前
【技术专题】HTML5 网页技术 - Web Storage 本地存储 & 文件 API & 拖放 API
前端·html·html5
恋猫de小郭5 分钟前
Flutter 官方表示:AI 时代代码越来越容易写,为什么还要一套代码库?
android·前端·flutter
软件派12 分钟前
Chrome 插件开发实战指南
前端·chrome
ly768912 分钟前
性能剖析与压测方法论:JMH、async-profiler 与分层瓶颈定位的可复现实验
服务器·前端·数据库·压测·jmh·性能剖析·async-profiler
ZoeLandia25 分钟前
React05:useEffect 与副作用
开发语言·前端·react.js·typescript
狮子座的男孩32 分钟前
html+css基础:24、2D变换(位移/缩放/旋转/扭曲(了解)/多重变换/变换原点)
前端·css·经验分享·html·2d位移·原点变换·缩放/旋转/扭曲
weixin_4173968341 分钟前
酒店弱电怎么验收?四个阶段与逐项检查清单
开发语言·前端·php·综合布线·弱电
风骏时光牛马41 分钟前
探索AI开源工具,解锁原生创造新体验
前端
u01110267544 分钟前
Vue 页面离开后还在轮询?统一清理计时器、监听器与观察器
前端·javascript·vue.js