React的createElement和render手寫實(shí)現(xiàn)示例
TL;DR
本文的目標(biāo)是,手寫實(shí)現(xiàn)createElement和render
- React.createElement實(shí)現(xiàn)的本質(zhì)就是整合參數(shù)變成對(duì)象,這個(gè)對(duì)象就是
react元素 - ReactDOM.render實(shí)現(xiàn)的本質(zhì)就是根據(jù)
react元素(對(duì)象)創(chuàng)建真實(shí)元素及其屬性和子元素
科普概念
- JSX 語(yǔ)法 - 就是類似 html 的寫法
<h1>顏醬<span>最酷</span></h1> - JSX 語(yǔ)法本質(zhì) - JSX 本質(zhì)是語(yǔ)法糖,實(shí)際會(huì)被 babel 編譯成
React.createElement - react 元素 - 并不是真實(shí) DOM,實(shí)際是
React.createElement函數(shù)返回的對(duì)象,結(jié)構(gòu)大約如下,核心屬性就是type、props、props.children
reactElement = {
type: 'div',
props: {
className: 'title',
style: { color: '#f69' },
children: 'world',
},
};
準(zhǔn)備工作
- 先創(chuàng)建一個(gè) react 項(xiàng)目:
create-react-app react-source
- 安裝
cross-env和修改命令,兼容 React 舊寫法
yarn add cross-env
修改package.json的命令:
"scripts": {
"start": "cross-env DISABLE_NEW_JSX_TRANSFORM=true react-scripts start",
"build": "cross-env DISABLE_NEW_JSX_TRANSFORM=true react-scripts build"
},
- 刪除 src 里面所有內(nèi)容,然后新建
index.js
import React from 'react';
import ReactDOM from 'react-dom';
const reactElement_text = 'only text';
const reactElement_oneNode = (
<div className="title" style={{ color: '#f69' }}>
one node
</div>
);
const reactElement_oneChildNode = (
<div>
<span>one child node</span>
</div>
);
const reactElement_multipleNode = (
<div>
<span>first child</span>
text child
</div>
);
// only text
console.log(reactElement_text);
// { type: 'div', props: { className: 'title', style: { color: '#f69' }, children: 'one node' }, };
console.log(reactElement_oneNode);
// { type: 'div', props: { children: { type: 'span', props: { children: 'one child node' }, }, }, };
console.log(reactElement_oneChildNode);
// { type: 'div', props: { children: [ { type: 'span', props: { children: 'first child node' } }, 'text', ], }, };
console.log(reactElement_multipleNode);
ReactDOM.render(reactElement_multipleNode, document.getElementById('root'));
留心看,props.children的結(jié)構(gòu),有三種類型:字符串、對(duì)象、數(shù)組。
- 啟動(dòng)項(xiàng)目
npm start
(^▽^),就可以看到http://localhost:3000/了!
實(shí)現(xiàn) createElement
JSX 語(yǔ)法相當(dāng)于React.createElement,那么先實(shí)現(xiàn)createElement。
先看看怎么相當(dāng),在線訪問:



- 分析參數(shù) - 輸入
- 第一個(gè)參數(shù),始終是最外層元素名
- 第二個(gè)參數(shù),始終是最外層的元素屬性集合 或
null - 第三個(gè)參數(shù)及以后的參數(shù),始終是子元素,沒有子元素的話,就沒有第三個(gè)參數(shù)
- 幾個(gè)子元素,就多幾個(gè)參數(shù),每個(gè)子元素的類型是
字符串或React.createElement()
- 分析返回值 - 輸出
- 對(duì)象,也叫
react元素 - 屬性 type 是元素名
- 屬性 props 是對(duì)象,里面是元素的屬性集合,props.children 可能是字符串、
react元素、數(shù)組(單項(xiàng)還是字符串 或react元素)
- 新建
source文件夾,建react.js。輸入和輸出已經(jīng)明了了,接下來就是將輸入變成輸出。
function createElement(type, config, ...children) {
console.log(type, config, ...children)
// children分 0個(gè) 單個(gè) 多個(gè)
const isNoneChildren = children.length === 0;
const isOneChildren = children.length === 1;
children = isNoneChildren
? null
: isOneChildren
? children[0]
: children;
const res = {
type,
props: {
...config,
children,
},
};
return res;
}
const React = {
createElement,
};
export default React;
實(shí)現(xiàn) render
render說白了就是將React元素轉(zhuǎn)化成真實(shí)DOM,插入到root容器中,從而自動(dòng)渲染。
- 分析參數(shù) - 輸入
- 第一個(gè)參數(shù),可能是
react元素、普通字符串、null - 第二個(gè)參數(shù),掛載的元素
- 分析返回值 - 無
- 分析執(zhí)行的結(jié)果 - 顯示第一個(gè)參數(shù)
render 執(zhí)行之后,將第一個(gè)參數(shù)變成真實(shí) DOM,插入到第二個(gè)參數(shù)掛載元素上,因?yàn)閽燧d元素本身存在于文檔之中,所以掛載操作會(huì)觸發(fā)渲染,顯示出來。因此,render本質(zhì)就是掛載
第一個(gè)參數(shù)變成真實(shí) DOM,本質(zhì)就是創(chuàng)建元素,增加屬性,增加 children
- 建
source/react-dom.js
function render(vdom, container) {
// 本質(zhì)就是掛載,因container本身存在于文檔之中,所以掛載操作會(huì)觸發(fā)渲染
mount(vdom, container);
}
function mount(vdom, container) {
// 將第一個(gè)參數(shù)變成真實(shí)DOM,插入到第二個(gè)參數(shù)掛載元素上
const DOM = createDOM(vdom);
container.append(DOM);
}
function createDOM(vdom) {
const isTextNode = typeof vdom === 'string' || vdom == null;
if (isTextNode) return document.createTextNode(vdom || '');
const isElementNode = typeof vdom === 'object';
if (isElementNode) return createElementDOM(vdom);
function createElementDOM(vdom) {
const { type, props } = vdom;
let DOM = document.createElement(type);
if (props) {
updateProps(DOM, props);
const { children } = props;
children && updateChildren(DOM, children);
}
return DOM;
}
}
function updateProps(DOM, props) {
console.log(DOM, props);
// 正常遍歷就好,特殊的特殊處理
for (const key in props) {
if (key === 'children') continue;
if (key === 'style') {
updateStyle(DOM, props[key]);
continue;
}
DOM[key] = props[key];
}
function updateStyle(DOM, styleObj) {
for (const key in styleObj) {
DOM.style[key] = styleObj[key];
}
}
}
function updateChildren(DOM, children) {
// 單個(gè)節(jié)點(diǎn),直接插入(掛載)到DOM上; 多個(gè)節(jié)點(diǎn),遍歷插入
const isOneChildren = !Array.isArray(children);
isOneChildren
? mount(children, DOM)
: children.forEach((child) => mount(child, DOM));
}
const ReactDOM = {
render,
};
export default ReactDOM;
測(cè)試
將index.js里面的react和react-dom換成我們寫的。
以上就是React的createElement和render手寫實(shí)現(xiàn)示例的詳細(xì)內(nèi)容,更多關(guān)于React createElement render的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
react配置webpack-bundle-analyzer項(xiàng)目?jī)?yōu)化踩坑記錄
這篇文章主要介紹了react配置webpack-bundle-analyzer項(xiàng)目?jī)?yōu)化踩坑記錄,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Next.js實(shí)現(xiàn)react服務(wù)器端渲染的方法示例
這篇文章主要介紹了Next.js實(shí)現(xiàn)react服務(wù)器端渲染的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01
淺談使用React.setState需要注意的三點(diǎn)
本篇文章主要介紹了淺談使用React.setState需要注意的三點(diǎn),提出了三點(diǎn)對(duì) React 新手來說是很容易忽略的地方,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12
React 條件渲染最佳實(shí)踐小結(jié)(7種)
這篇文章主要介紹了React 條件渲染最佳實(shí)踐小結(jié)(7種),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
React使用TypeScript的最佳實(shí)踐和技巧
在React項(xiàng)目中使用TypeScript可以顯著提高代碼的可維護(hù)性和可讀性,并提供強(qiáng)大的類型檢查功能,減少運(yùn)行時(shí)錯(cuò)誤,以下是一些優(yōu)雅地將TypeScript集成到React項(xiàng)目中的最佳實(shí)踐和技巧,需要的朋友可以參考下2024-06-06

