美文网首页
一、实现最简单的mini-react

一、实现最简单的mini-react

作者: sweetBoy_9126 | 来源:发表于2024-03-22 22:23 被阅读0次

1. 使用最简单的 js 创建一个元素并渲染到页面上

const dom = document.createElement('div')
dom.id = 'dom'
document.querySelector('#root').append(dom)

const text = document.createTextNode('')
text.nodeValue = 'app'
dom.append(text)

2. 实现基础的 vdom 渲染

上面的div 和 text 如果看做 Object 会有 type props children 属性

// type -> div/textNode
// props -> {id: 'dom} 
const textEl = {
    type: 'TEXT_ELEMENT',
    props: {
      nodeValue: 'app',
      children: []
    },
}
const el = {
  type: 'div',
  props: {
    id: 'dom',
    children: [
      textEl
     ]
  },
}
const dom = document.createElement(el.type)
dom.id = el.props.id
document.querySelector('#root').append(dom)

const text = document.createTextNode('')
text.nodeValue = textEl.props.nodeValue
dom.append(text)

3. 动态创建 vdom

const createTextNode = (text) => {
  return {
    type: 'TEXT_ELEMENT',
    props: {
      nodeValue: text,
      children: []
    },  
  }
}

const createElement = (type, props, ...children) => {
  return {
    type,
    props,
    children
  }
}
const textEl = createTextNode('app')
const App = createElement('div', {id: 'div'}, textEl)

const dom = document.createElement(App.type)
dom.id = App.props.id
document.querySelector('#root').append(dom)

const text = document.createTextNode('')
text.nodeValue = textEl.props.nodeValue
dom.append(text)

4. 动态创建dom节点

分析上面的代码

  1. 创建一个节点
  2. 设置 props
  3. 当前节点的父级添加当前节点
const createTextNode = (text) => {
  return {
    type: 'TEXT_ELEMENT',
    props: {
      nodeValue: text,
    },
      children: []
  }
}

const createElement = (type, props, ...children) => {
  return {
    type,
    props,
    children
  }
}

const render = (el, container) => {
  // 1. 创建节点
  const dom = el.type === 'TEXT_ELEMENT' ? document.createTextNode('') : document.createElement(el.type)
  // 2. 设置 props
  Object.keys(el.props).forEach(attr => {
    if (attr !== 'children') {
      dom[attr] = el.props[attr]
    }
  })

  // 对孩子节点进行同样的处理
  if (el.children && el.children.length) {
    el.children.forEach((child) => render(child, dom))
  }
  
  // 3. 父级容器添加当前节点 
  container.append(dom)
}
const textEl = createTextNode('app')
const App = createElement('div', {id: 'div'}, textEl)
render(App, document.querySelector('#root'))
  • 优化:
    我们想直接调用 createElement 的时候 children 传字符串,不想再去调用 createTextNode 后传入
const App = createElement('div', {id: 'div'}, 'app')
  • 实现:
    只需要在遍历 children 的时候判断传入的类型是否是字符串,如果是字符串直接调用 createTextNode
const createElement = (type, props, ...children) => {
  return {
    type,
    props,
 +   children: children.map((child) => {
        return typeof child === 'string' ? createTextNode(child) : child
     })
  }
}

5. 改写成 react 的 api

// ReactDom.createRoot(document.getElementById('#root').render(<App />))

const ReactDOM = {
  createRoot(container) {
    return {
      render(app) {
        return render(app, container)
      }
    }
  }
}
const App = createElement('div', {id: 'div'}, 'app')
ReactDOM.createRoot(document.querySelector('#root')).render(App)

5.1. 重构

  • core/ReactDom.js
import React from './React.js'
const ReactDOM = {
  createRoot(container) {
    return {
      render(app) {
        React.render(app, container)
      }
    }
  }
}
export default ReactDOM
  • core/React.js
const createTextNode = (text) => {
  return {
    type: 'TEXT_ELEMENT',
    props: {
      nodeValue: text,
    },
      children: []
  }
}

const createElement = (type, props, ...children) => {
  return {
    type,
    props,
    children
  }
}

const render = (el, container) => {
  
  const dom = el.type === 'TEXT_ELEMENT' ? document.createTextNode('') : document.createElement(el.type)
  
  Object.keys(el.props).forEach(attr => {
    if (attr !== 'children') {
      dom[attr] = el.props[attr]
    }
  })

  if (el.children && el.children.length) {
    el.children.forEach((child) => render(child, dom))
  }
  container.append(dom)
}

const React = {
  render,
  createElement,
}
export default React
  • App.js
import React from './core/React.js'
const App = React.createElement('div', {id: 'div'}, 'app')
export default App
  • main.js
import ReactDom from './core/ReactDom.js'
import App from './App.js'

ReactDom.createRoot(document.querySelector('#root')).render(App)

6. 使用 jsx

对于我们上面的代码我们直接将我们的 App.js 改成 App.jsx 会报错


  • 原因:
    浏览器不认识 jsx 只认识 js
    解决方法:将 jsx 转成 js

6.1. 使用 vite将 jsx 转成 js

  1. 创建 vite 项目
pnpm create vite
  1. 将我们的代码复制到生成的 vite 项目里
  2. 改写我们的jsx用法
// 之前的写法
// const App = React.createElement('div', {id: 'div'}, 'app')

// 新的写法
const App = <div>app</div>

如果我们打印我们的App就会看到控制台得到的就是我们之前生成的 vdom 节点

{
  type: 'div',
  props: {
      children: [
        {
          type: 'TEXT_ELEMENT',
          props: {
            nodeValue: 'app',
            children: []
          }
        }
      ]
  }
}

我们可以通过一个函数返回一个dom节点然后打印这个函数来看它到底做了什么

const AppOne = () => {
  return <div id='dom'>app</div>
}
console.log(AppOne)

我们会得到

() => {
    return /* @__PURE__ */ React.createElement("div", { id: "dom" }, "app");
  }

所以之所以我们可以直接通过 const App = <div id="dom">app</div>来创建元素,就是因为它本身调用了我们写的那个React.createElement 帮我们处理了

6.1.1.自定义 react 的名字
  • 需求:
    我们上面打印的AppOne 里是调用的 React.createElement,如果我们想让它叫一个其他的名字比如 lifaReact 我们该如何
  • 实现:
    我们只需要在每个 jsx 文件顶部加一行注释
/**@jsx lifaReact.createElement */

这样每次使用jsx的时候都会使用我们自定义的名字而不是默认的 React.createElement,但是需要注意的是每个jsx 文件头部都要写这一段

相关文章

网友评论

      本文标题:一、实现最简单的mini-react

      本文链接:https://www.haomeiwen.com/subject/exdctjtx.html