自己动手实现react
实现简易 React 的核心功能
React 的核心功能包括虚拟 DOM、组件化、状态管理和 diff 算法。以下分步骤实现这些功能:
虚拟 DOM 的实现
虚拟 DOM 是真实 DOM 的轻量级 JavaScript 表示。可以通过对象结构来描述 DOM 元素:
function createElement(type, props, ...children) {
return {
type,
props: {
...props,
children: children.map(child =>
typeof child === "object" ? child : createTextElement(child)
)
}
}
}
function createTextElement(text) {
return {
type: "TEXT_ELEMENT",
props: {
nodeValue: text,
children: []
}
}
}
渲染函数实现
将虚拟 DOM 渲染到真实 DOM 上:

function render(element, container) {
const dom =
element.type === "TEXT_ELEMENT"
? document.createTextNode("")
: document.createElement(element.type)
const isProperty = key => key !== "children"
Object.keys(element.props)
.filter(isProperty)
.forEach(name => {
dom[name] = element.props[name]
})
element.props.children.forEach(child =>
render(child, dom)
)
container.appendChild(dom)
}
组件系统实现
创建基础的组件系统,支持函数组件和类组件:
function createComponent(component, props) {
if (component.prototype && component.prototype.render) {
// 类组件
const instance = new component(props)
return instance.render()
} else {
// 函数组件
return component(props)
}
}
状态管理
实现基础的 useState Hook:

let state = []
let index = 0
function useState(initialState) {
const currentIndex = index
state[currentIndex] = state[currentIndex] || initialState
function setState(newState) {
state[currentIndex] = newState
// 触发重新渲染
renderApp()
}
index++
return [state[currentIndex], setState]
}
function renderApp() {
index = 0
// 重新渲染应用
}
Diff 算法实现
简单的 DOM diff 算法,仅对比节点类型:
function updateDom(dom, prevProps, nextProps) {
// 移除旧属性
Object.keys(prevProps)
.filter(isProperty)
.forEach(name => {
if (!(name in nextProps)) {
dom[name] = ""
}
})
// 设置新属性
Object.keys(nextProps)
.filter(isProperty)
.forEach(name => {
if (prevProps[name] !== nextProps[name]) {
dom[name] = nextProps[name]
}
})
}
完整示例
将这些部分组合起来创建一个简单的 React 实现:
const MyReact = {
createElement,
render,
useState,
Component: class Component {
constructor(props) {
this.props = props
this.state = {}
}
setState(partialState) {
this.state = { ...this.state, ...partialState }
renderApp()
}
}
}
// 使用示例
function App() {
const [count, setCount] = MyReact.useState(0)
return MyReact.createElement(
"div",
null,
MyReact.createElement("h1", null, "Count: ", count),
MyReact.createElement(
"button",
{ onClick: () => setCount(count + 1) },
"Increment"
)
)
}
function renderApp() {
const element = MyReact.createElement(App, null)
const container = document.getElementById("root")
container.innerHTML = ""
MyReact.render(element, container)
}
renderApp()
性能优化方向
- 实现更高效的 diff 算法(如 React 的 Fiber 架构)
- 添加 shouldComponentUpdate 生命周期方法
- 实现 key 属性优化列表渲染
- 添加 useEffect 等更多 Hooks
- 实现事件委托系统
这个实现展示了 React 的核心概念,实际 React 实现更加复杂,包括调度器、优先级系统等高级功能。






