ReactElement 原始碼筆記
ReactElement通過 createElement創建,呼叫該方法需要 傳入三個引數:
- type
- config
- children
type指代這個ReactElement 的型別
config指代這個ReactElement 的屬性物件
children指代這個ReactElement 的子元素節點
- 字串比如
'div','p'代表原生DOM,稱為HostComponent - Class 型別是我們繼承自
Component或者PureComponent的組件,稱為ClassComponent - 方法就是
function Component - 原生提供的
Fragment、AsyncMode等是 Symbol,會被特殊處理 - TODO: 是否有其他的
//原始碼位置: packages/react/src/ReactElement.js
// createElement函式
export function createElement(type, config, children){
// 一、處理config
// 1. 判斷config是否為空
// 2. 提取保留屬性(key, ref, self, soure)
// 3. 其余屬性添加到新的props物件中
for(propName in config){
if(
hasOwnProperty.call(config, propName)&&
!RESERVED_PROPS.hasOwnProperty(propName)
){
props[propName] = config[propName]
}
}
// 二、處理children => props.children
// (children可以超過一個),處理過后的children 被放入 props.children
const childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
const childArray = Array(childrenLength);
for (let i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
// 三、處理type的 defaultProps
if(type && type.defaultProps) {
const defaultProps = type.defaultProps;
for (propName in defaultProps) {
if(props[propName] === undefined) {
props[propName] = defaultProps[propName]
}
}
}
// 四、回傳一個ReactElement()函式
return ReactElement(
type,
key,
ref,
self,
source,
ReactCurrentOwner.current,
props,
);
}
注:
type.defaultProps的由來:
- 定義一個ClassComponent:
class Comp extends React.Component- 可以為
Comp設定一個defaultProps:Comp.defaultProps = { value: 1 }
//原始碼位置: packages/react/src/ReactElement.js
// ReactElement 函式
const ReactElement = function(type, key, ref, self, source, owner, props){
const element = {
// $$typeof用于標識 Element 是什么型別的
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner,
}
// _DEV_ 代碼...
return element;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/265622.html
標籤:其他
上一篇:使用CSS計數器美化數字有序串列
