React高階元件入門

2021-10-01 15:04:27 字數 4055 閱讀 9375

在了解高階元件之前我們先了解高階函式是什麼:

函式可以被作為引數傳遞;

settimeout((

)=>

,1000

)

函式可以作為返回值輸出;

function

foo( x )

}

高階函式的應用

高階函式在時間函式上的應用

settimeout

(function()

,1000

)setinterval((

)=>

,1000

);

高階函式在jquery ajax中的應用

$.

get(

"/api/getuserinfo"

,function

(res)

)

es5中陣列的迭代方法:

some() 、every() 、filter()、map()、foreach()
高階元件就是接受乙個元件作為引數並返回乙個新元件的函式,高階元件是乙個函式,並不是元件

高階元件示例;

functiona}

}

為什麼需要高階元件

多個元件需要相同的功能,使用高階元件減少重複實現,react-redux中的connect函式就是高階元件

export

default

connect

(mapstatetoprops,mapdispatchtoprops)

(header)

變寫普通元件

將普通元件使用函式包裹

// 編寫普通元件

class

dextends

component

}

// 定義乙個函式包裹剛剛編寫的元件

import react,

from

'react'

functiond(

)}}//高階函式編寫完成將其匯出

export

default d

使用高階元件

//直接呼叫  

higherordercomponent

//使用裝飾器語法,注意:使用裝飾器需要安裝相關的外掛程式

@higherordercomponent

返回的新元件直接繼承自react.component類,,新元件扮演的角色是傳入引數元件的乙個**,在新的元件的render函式中,將被包裹元件渲染出來,除了高階元件自己要做的工作,其餘功能全部都轉手給了被包裹的元件

export

default()

class

aextends

component

=this

.props

return

...otherprops}

/>

}}

export

default()

class

aextends

=this

.props

this

.props = otherprops

return

super

.render()

}}

1.操縱prop: 高階元件能夠改變被包裹元件的props

//props的增加

export

default

(title)

class

aextends

component

<

/div>

/>

<

/div>)}

}//props的刪減

export

default

(title)

class

aextends

component

=this

.props 刪除age這個屬性值

return

(<

/div>

/>

<

/div>)}

}

2.訪問ref :獲取被包裝元件的例項

export

default

(title)

class

aextends

component

render()

=this

.props 刪除age這個屬性值

return

(<

/div>

ref=

/>

<

/div>)}

}//使用

import

afrom

'./a'

@a("我是元件e"

)class

eextends

component

render()

}export

default

e

抽取狀態

export

default

(title)

class

aextends

component

}oninputchange

=(e)

=>

}render()

return

(<

/div>

...newprops}

/>

<

/div>)}

}

// 使用

import

afrom

'./a'

@a("我是元件e"

)class

fextends

component

render()

/>

<

/div>)}

}export

default

f

1.操縱prop: 高階元件能夠改變被包裹元件的props

const

modifyhoc

=>

class

aextends

const newprops =

return react.

cloneelement

(element,newprops,element.props.children)}}

//使用

import react,

from

'react'

import modify from

'./d'

@modify

class

gextends

from component

}

1.操縱生命週期函式:

const

modifyhoc

=>

class

aextends

render()

const newprops =

return react.

cloneelement

(element,newprops,element.props.children)}}

//使用

import react,

from

'react'

import modify from

'./d'

@modify

class

gextends

from component

render()

}

React高階元件入門

react高階元件入門 react高階元件也差不多快要退出主流舞台了,我是因為初學,所以記錄一下自己的理解 簡介 有點像vue的mixin 物件混入 封裝公共模組。不過react並不提倡這種做法,所以引入了一種新的概念叫高階元件 hoc 乙個函式,能夠接受乙個元件並返回乙個新的元件。命題乙個模組需要...

React 高階元件入門介紹

高階元件的定義 hoc 不屬於 react 的 api,它是一種實現模式,本質上是乙個函式,接受乙個或多個 react 元件作為引數,返回乙個全新的 react 元件,而不是改造現有的元件,這樣的元件被稱為高階元件。開發過程中,有的功能需要在多個元件類復用時,這時可以建立乙個 hoc。基本用法 包裹...

React高階元件

想想以前用原生和jquery的專案,上千行的code映入眼簾,瞬間有種昏死過去的衝動。難以維護,改乙個bug可能出現n個bug,真的是很痛苦。於是乎元件化成為了當前前端開發的主流技術。angular vue和react很好的幫我們實現了元件化。但是我們常常也會遇到一種情況,就是兩個元件往往有很多的重...