-
ReactDom
ReactDom是一个js对象,是用户写的ReactDOM和浏览器中的DOM之间的映射表,用以构建 DOM 以及保持随时更新。import React, { Component } from 'react'; import { render } from 'react-dom'; let element = <h1 id="title">hello<h2>word</h2></h1>; console.log(element) render(element, document.getElementById('root'));babel会将以上代码编译成:
var element = React.createElement("h1", { id: "title" }, "hello", React.createElement("h2", null, "word"));React.createElement的实现原理基本如下:
function createElement(type, options={}, ...children){ return { type, props: {...options, children} } }这样,element就是一个含有type、props这两个核心属性的嵌套对象。
-
JSX的Tips
根据JSX渲染引擎原理,JSX语法需要注意以下几点:- 避免使用js关键字,并使用小驼峰规则,如class --> className;
- 为了高效DOM diff,列表中要加上key属性;
- ReactDom是不可变对象,不可以通过修改props属性来重新渲染DOM;
- 重复渲染也会进行DOMdiff。会尽可能复用原有DOM,只更新必要DOM。
-
React.createElement基本原理
const hasSymbol = typeof symbol == "function" && symbol.for; const REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 0xeac7; function createElement(type, config, children) { let props = {}; for (let key in config) { props[key] = config[key]; } const childrenLength = arguments.length - 2; if (childrenLength == 1) { props.children = children; } else if (childrenLength > 1) { props.children = Array.prototype.slice.call(arguments, 2); } return { $$typeof: REACT_ELEMENT_TYPE, type, props }; } class Component { constructor(props) { this.props = props; } static isReactComponent = true; } export default { createElement, Component }; -
ReactDom.render的基本原理
/** *@param {*} node React节点,可能的值为:React元素、数字、字符串 *@param {*} parent 父容器,是一个真实DOM元素 */ function render(node, parent) { if (typeof node === "string") { return parent.appendChild(document.createTextNode(node)); } let type, props; type = node.type; props = node.props; if(type.isReactComponent){//如果是类组件 let element = new type(props).render(); type = element.type; props = element.props; if(typeof element.type == 'function'){//如果类组件返回的是函数组件 return render(element, parent) } }else if (typeof type === "function") {//如果是函数组件~~~~ let element = type(props); type = element.type; props = element.props; if(typeof element.type == 'function'){ return render(element, parent) } } let domElement = document.createElement(type); //创建真实的DOM元素 for (let propName in props) { if (propName == "children") { // 如果是children,则递归遍历 let children = props.children; if (!Array.isArray(children)) {//如果不是数组,则变为数组 children = [children]; } children.forEach(child => render(child, domElement)); } else if (propName === "className") { domElement.className = props.className; } else if (propName === "style") { let styleObject = props.style; for (let attr in styleObject) domElement.style[attr] = styleObject[attr]; } else { domElement.setAttribute(propName, props[propName]); } } parent.appendChild(domElement); } export default { render };
1.react入门-JSX
点赞
收藏


