实现简易react
实现简易 React 的核心要素
要实现一个简易 React,需要模拟其核心功能:虚拟 DOM、组件化、状态管理和渲染机制。以下是关键步骤和代码示例。
虚拟 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 中。递归处理虚拟 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);
}
组件和状态管理
实现一个简单的函数组件和状态管理机制。使用闭包和钩子模拟 useState:
let currentHook = null;
let hookIndex = 0;
let componentInstance = null;
function useState(initialState) {
const hooks = componentInstance.hooks;
const existingHook = hooks[hookIndex];
const hook = {
state: existingHook ? existingHook.state : initialState,
queue: [],
};
const actions = existingHook ? existingHook.queue : [];
actions.forEach(action => {
hook.state = typeof action === 'function' ? action(hook.state) : action;
});
const setState = action => {
hook.queue.push(action);
// 触发重新渲染
render(componentInstance.element, componentInstance.container);
};
hooks[hookIndex] = hook;
hookIndex++;
return [hook.state, setState];
}
function createComponent(fn, props) {
return {
fn,
props,
hooks: [],
element: null,
container: null,
};
}
示例使用
将上述功能组合起来,实现一个简单的计数器组件:
function Counter() {
const [count, setCount] = useState(0);
return createElement('div', null,
createElement('h1', null, 'Count: ', count),
createElement('button', { onClick: () => setCount(c => c + 1) }, 'Increment')
);
}
const container = document.getElementById('root');
const element = createElement(Counter, null);
componentInstance = createComponent(Counter, null);
componentInstance.element = element;
componentInstance.container = container;
render(element, container);
功能扩展
为完善功能,可以进一步实现以下内容:
- Diff 算法:比较新旧虚拟 DOM 的差异,仅更新变化的部分。
- 生命周期钩子:模拟
componentDidMount和componentDidUpdate。 - 事件系统:规范化事件处理,如
onClick的合成事件。
以上代码展示了 React 的核心思想,实际实现中还需处理更多边界条件和性能优化。







