您當前的位置:首頁 > 動漫

react 原始碼中的createElement 方法解讀

作者:由 劈哩叭啦 發表于 動漫時間:2022-12-11

createElement 方法

function

createElement

type

config

children

){

//步驟一。處理config

for

propName

in

config

{

if

hasOwnProperty

call

config

propName

&&

RESERVED_PROPS

hasOwnProperty

propName

))

{

props

propName

=

config

propName

];

}

}

//步驟2:處理children

var

childrenLength

=

arguments

length

-

2

if

childrenLength

===

1

{

props

children

=

children

}

else

if

childrenLength

>

1

{

var

childArray

=

Array

childrenLength

);

for

var

i

=

0

i

<

childrenLength

i

++

{

childArray

i

=

arguments

i

+

2

];

}

{

if

Object

freeze

{

Object

freeze

childArray

);

}

}

props

children

=

childArray

}

//步驟3:處理defaultProps

if

type

&&

type

defaultProps

{

var

defaultProps

=

type

defaultProps

for

propName

in

defaultProps

{

if

props

propName

===

undefined

{

props

propName

=

defaultProps

propName

];

}

}

}

return

ReactElement

type

key

ref

self

source

ReactCurrentOwner

current

props

);

}

一、處理config

如果config中有key,ref ,

self,

source 屬性,單領出來;

config中除了key,ref,self,source屬性之外的其他屬性遍歷到props裡面;

二、處理children

從第三個引數開始都是children;

只有一個children,直接賦值給props。children;

如果大於1,把children按個數遍歷成為一個數組,陣列成員為每一個children;

凍結陣列,外界不能新增、刪除、修改陣列;

把這個陣列賦值給props。children;

三、處理defaultProps

判斷defaultProps中的屬性是否在props上面存在,不存在新增屬性

最後去呼叫 reactElement()並返回reactNode;

標簽: Children  props  propName  config  type