React元件復用

2021-10-13 19:44:19 字數 1825 閱讀 3812

目錄

react元件復用概述

render props 模式

使用步驟

2. 高階元件

思路分析

使用步驟

設定displayname

傳遞 props

思路分析

{} />
(

滑鼠當前位置 ,

) />

建立mouse元件 , 在元件中提供復用的狀態邏輯** ( 1. 狀態 2. 操作狀態的方法 )

將要復用的狀態作為 props.render( state ) 方法的引數 , 暴露到元件外部

使用 props.render() 的返回值作為要渲染的內容

class mouse extends react.component 

handlemousemove = e => )

} componentdidmount()

render()

} render()

}

class mouse extends react.component 

} render() ,

/>

)}}

**優化:

1. 推薦: 給 render props 模式新增 props 校驗

2. 應該在元件解除安裝時解除mousemove 事件繫結

mouse.proptypes =
componentwillumount()
概述:

// withhoc 高階元件

// 高階元件內部建立的類元件:

class mouse extends react.component

建立乙個函式 , 名稱約定以with開頭

指定函式引數 , 引數應該以大寫字母開頭 ( 作為要渲染的元件 )

在函式內部建立乙個類元件 , 提供復用的狀態邏輯** , 並返回

在該元件中 , 渲染引數元件 , 同事將狀態通過prop傳遞給引數元件 

呼叫高階元件 , 傳入要增強的元件 , 通過返回值拿到增強後的元件 , 並將其渲染到頁面中  

// 建立乙個函式 , 名稱約定以with開頭

function withmouse(){}

//指定函式引數 , 引數應該以大寫字母開頭 ( 作為要渲染的元件 )
//在函式內部建立乙個類元件 , 提供復用的狀態邏輯** , 並返回

function withmouse(warppedcomponent)

return mouse

}

// 建立高階元件

// 該元件提供復用的狀態邏輯

class mouse extends react.component

handlemousemove = e => )

}//控制滑鼠狀態邏輯

componentdidmount()

//解綁事件

componentwillunmount()

render()

} return mouse

}//用來測試高階元件

const position = props => (

滑鼠當前位置:(x:,y:) )

const mousepositon = withmouse(position)

render() */}

)}}

React元件化復用的一些技巧

復用是元件化開發體系的立命之本,可以說元件化的初衷就是為了復用性。但是元件化的復用方式也存在一定的問題,其中拆分粒度就是其中乙個繞不開的話題,今天咱們就來講一講 react 當中的乙個不太常用的 api cloneelement,他如何幫組我們更好得進行元件拆分。假如我們有乙個layout元件,那麼...

react 元件復用判斷div在左邊還是右邊

父元件 父元件裡面無需定義isright,只需要在傳遞乙個isright給子元件,其他沒傳遞的是預設為true 子元件接收 用props接收 右邊div function rightbox src div function classfiybox props props return 如果!isri...

專案復用元件

下拉框選擇器 收款銀行 queryinfo.companyaccount clearable for item in banklist key item.id label item.opttext value item.optvalue el option el select el form ite...