如何手写一个react
手写一个简单的 React 实现
理解 React 的核心概念包括虚拟 DOM、组件化和状态管理。以下是一个简化版 React 的实现方法,涵盖基本功能。
创建虚拟 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(type, props) {
return type(props);
}
function App(props) {
return createElement("div", null, `Hello ${props.name}`);
}
const element = createElement(App, { name: "World" });
render(element, document.getElementById("root"));
实现状态管理
使用闭包实现基础 useState:

let state;
function useState(initial) {
const setState = newState => {
state = newState;
rerender();
};
if (state === undefined) state = initial;
return [state, setState];
}
function rerender() {
// 实现重新渲染逻辑
}
实现协调算法
简化版 diff 算法实现 DOM 更新:
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];
}
});
}
实现生命周期
基础组件生命周期模拟:
function useEffect(callback, deps) {
const hasChanged = !deps || deps.some((dep, i) => dep !== previousDeps[i]);
if (hasChanged) {
callback();
previousDeps = deps;
}
}
这个简化实现包含了 React 的核心概念。实际 React 源码更复杂,包含性能优化、错误边界等更多功能。可以通过逐步添加更多功能来完善这个实现。






