面試官:說說React Jsx轉換成真實DOM過程?
本文轉載自微信公眾號「JS每日一題」,作者灰灰。轉載本文請聯系JS每日一題公眾號。
一、是什么
react通過將組件編寫的JSX映射到屏幕,以及組件中的狀態(tài)發(fā)生了變化之后 React會將這些「變化」更新到屏幕上
在前面文章了解中,JSX通過babel最終轉化成React.createElement這種形式,例如:
- <div>
- <img src="avatar.png" className="profile" />
- <Hello />
- </div>
會被bebel轉化成如下:
- React.createElement(
- "div",
- null,
- React.createElement("img", {
- src: "avatar.png",
- className: "profile"
- }),
- React.createElement(Hello, null)
- );
在轉化過程中,babel在編譯時會判斷 JSX 中組件的首字母:
- 當首字母為小寫時,其被認定為原生 DOM 標簽,createElement 的第一個變量被編譯為字符串
- 當首字母為大寫時,其被認定為自定義組件,createElement 的第一個變量被編譯為對象
最終都會通過RenderDOM.render(...)方法進行掛載,如下:
- ReactDOM.render(<App />, document.getElementById("root"));
二、過程
在react中,節(jié)點大致可以分成四個類別:
- 原生標簽節(jié)點
- 文本節(jié)點
- 函數組件
- 類組件
如下所示:
- class ClassComponent extends Component {
- static defaultProps = {
- color: "pink"
- };
- render() {
- return (
- <div className="border">
- <h3>ClassComponent</h3>
- <p className={this.props.color}>{this.props.name}</p>
- </div>
- );
- }
- }
- function FunctionComponent(props) {
- return (
- <div className="border">
- FunctionComponent
- <p>{props.name}</p>
- </div>
- );
- }
- const jsx = (
- <div className="border">
- <p>xx</p>
- <a href="https://www.xxx.com/">xxx</a>
- <FunctionComponent name="函數組件" />
- <ClassComponent name="類組件" color="red" />
- </div>
- );
這些類別最終都會被轉化成React.createElement這種形式
React.createElement其被調用時會傳?標簽類型type,標簽屬性props及若干子元素children,作用是生成一個虛擬Dom對象,如下所示:
- function createElement(type, config, ...children) {
- if (config) {
- delete config.__self;
- delete config.__source;
- }
- // ! 源碼中做了詳細處理,⽐如過濾掉key、ref等
- const props = {
- ...config,
- children: children.map(child =>
- typeof child === "object" ? child : createTextNode(child)
- )
- };
- return {
- type,
- props
- };
- }
- function createTextNode(text) {
- return {
- type: TEXT,
- props: {
- children: [],
- nodeValue: text
- }
- };
- }
- export default {
- createElement
- };
createElement會根據傳入的節(jié)點信息進行一個判斷:
- 如果是原生標簽節(jié)點, type 是字符串,如div、span
- 如果是文本節(jié)點, type就沒有,這里是 TEXT
- 如果是函數組件,type 是函數名
- 如果是類組件,type 是類名
虛擬DOM會通過ReactDOM.render進行渲染成真實DOM,使用方法如下:
- ReactDOM.render(element, container[, callback])
當首次調用時,容器節(jié)點里的所有 DOM 元素都會被替換,后續(xù)的調用則會使用 React 的 diff算法進行高效的更新
如果提供了可選的回調函數callback,該回調將在組件被渲染或更新之后被執(zhí)行
render大致實現方法如下:
- function render(vnode, container) {
- console.log("vnode", vnode); // 虛擬DOM對象
- // vnode _> node
- const node = createNode(vnode, container);
- container.appendChild(node);
- }
- // 創(chuàng)建真實DOM節(jié)點
- function createNode(vnode, parentNode) {
- let node = null;
- const {type, props} = vnode;
- if (type === TEXT) {
- node = document.createTextNode("");
- } else if (typeof type === "string") {
- node = document.createElement(type);
- } else if (typeof type === "function") {
- node = type.isReactComponent
- ? updateClassComponent(vnode, parentNode)
- : updateFunctionComponent(vnode, parentNode);
- } else {
- node = document.createDocumentFragment();
- }
- reconcileChildren(props.children, node);
- updateNode(node, props);
- return node;
- }
- // 遍歷下子vnode,然后把子vnode->真實DOM節(jié)點,再插入父node中
- function reconcileChildren(children, node) {
- for (let i = 0; i < children.length; i++) {
- let child = children[i];
- if (Array.isArray(child)) {
- for (let j = 0; j < child.length; j++) {
- render(child[j], node);
- }
- } else {
- render(child, node);
- }
- }
- }
- function updateNode(node, nextVal) {
- Object.keys(nextVal)
- .filter(k => k !== "children")
- .forEach(k => {
- if (k.slice(0, 2) === "on") {
- let eventName = k.slice(2).toLocaleLowerCase();
- node.addEventListener(eventName, nextVal[k]);
- } else {
- node[k] = nextVal[k];
- }
- });
- }
- // 返回真實dom節(jié)點
- // 執(zhí)行函數
- function updateFunctionComponent(vnode, parentNode) {
- const {type, props} = vnode;
- let vvnode = type(props);
- const node = createNode(vvnode, parentNode);
- return node;
- }
- // 返回真實dom節(jié)點
- // 先實例化,再執(zhí)行render函數
- function updateClassComponent(vnode, parentNode) {
- const {type, props} = vnode;
- let cmp = new type(props);
- const vvnode = cmp.render();
- const node = createNode(vvnode, parentNode);
- return node;
- }
- export default {
- render
- };
三、總結
在react源碼中,虛擬Dom轉化成真實Dom整體流程如下圖所示:
其渲染流程如下所示:
- 使用React.createElement或JSX編寫React組件,實際上所有的 JSX 代碼最后都會轉換成React.createElement(...) ,Babel幫助我們完成了這個轉換的過程。
- createElement函數對key和ref等特殊的props進行處理,并獲取defaultProps對默認props進行賦值,并且對傳入的孩子節(jié)點進行處理,最終構造成一個虛擬DOM對象
- ReactDOM.render將生成好的虛擬DOM渲染到指定容器上,其中采用了批處理、事務等機制并且對特定瀏覽器進行了性能優(yōu)化,最終轉換為真實DOM
參考文獻
https://bbs.huaweicloud.com/blogs/265503)
https://huang-qing.github.io/react/2019/05/29/React-VirDom/
https://segmentfault.com/a/1190000018891454