React Render Props共享代碼技術(shù)
介紹
Render Props
是指在React組件之間使用一個值為函數(shù)
的prop共享代碼的技術(shù)- 具有
render prop
的組件接受一個返回React元素的函數(shù)
,并在組件內(nèi)部通過調(diào)用此函數(shù)來實現(xiàn)自己的渲染邏輯 - 主要用于抽離邏輯,進行代碼復(fù)用
使用
以官方文檔的Mouse & Cat
示例為例
- 創(chuàng)建
Mouse
組件,此組件僅用于提供復(fù)用的狀態(tài)邏輯代碼(狀態(tài)、方法等) - 將復(fù)用的狀態(tài)作為
props.render(state)
方法的參數(shù),暴露到組件外部 - 使用
props.render()
的返回值作為要渲染的內(nèi)容
import React from 'react' class Mouse extends React.Component { // 省略操作方法 render(){ return this.props.render(this.state) } } //根組件 export default class App extends React.Component { render(){ <Mouse render={ mouse => ( <div>當前鼠標位置 {mouse.x} {mouse.y}<div> )}/> //此處的mouse參數(shù)實際上為Mouse組件的state,因為這個函數(shù)是在Mouse組件的render()中傳參調(diào)用的 } }
注意:并不是該模式名叫render props
就一定要用名為render
的prop
。你可以使用任意名稱的prop
,它只是一個接收返回React元素的函數(shù)的prop
。
實際上,視圖是由父組件傳入的返回React元素的函數(shù)決定的,Mouse
組件中的render()
生命周期函數(shù)只是調(diào)用這個由prop
傳入的函數(shù),并由該函數(shù)返回視圖
使用children prop代替render prop
也可以使用組合模式來實現(xiàn)組件間的代碼重用,該方法類似于Vue中Slot
的概念
import React from 'react' class Mouse extends React.Component { // 省略操作方法 render(){ return this.props.children(this.state) } } //根組件 export default class App extends React.Component { render(){ <Mouse> { mouse => ( <div>當前鼠標位置 {mouse.x} {mouse.y}<div> )} </Mouse> } }
由于這一技術(shù)需要向組件傳遞一個函數(shù),所以推薦對children
進行類型檢查
import PropTypes from 'prop-types' Mouse.propTypes = { children: PropTypes.func.isRequired }
Render props 與 React.PureComponent 同時使用
注意
如果在render
方法中創(chuàng)建函數(shù),那么使用render prop
會抵消使用React.PureComponent
帶來的優(yōu)勢
因為每次調(diào)用render()
進行渲染時都會創(chuàng)建一個新的函數(shù),這將導(dǎo)致淺比較props
的時候prevProps === nextProps
始終為false
class Mouse extends React.PureComponent { // 與上面相同的代碼...... } class MouseTracker extends React.Component { render() { return ( <div> <Mouse render={mouse => ( <Cat mouse={mouse} /> )}/> </div> ); } }
在這個示例中,由于Mouse
組件的render prop
傳輸?shù)暮瘮?shù)是在render()
中定義的,這將導(dǎo)致每次MouseTracker
渲染時生成一個新的函數(shù)作為Mouse
組件的render prop
,因而抵消了繼承自React.PureComponent
的效果
解決方案
為了解決這一問題,可以定義一個實例方法傳給render prop
class MouseTracker extends React.Component { // 定義為實例方法,`this.renderTheCat`始終 // 當我們在渲染中使用它時,它指的是相同的函數(shù) renderTheCat(mouse) { return <Cat mouse={mouse} />; } render() { return ( <div> <h1>Move the mouse around!</h1> <Mouse render={this.renderTheCat} /> </div> ); } }
到此這篇關(guān)于React Render Props共享代碼技術(shù)的文章就介紹到這了,更多相關(guān)React Render Props內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文詳解ReactNative狀態(tài)管理rematch使用
這篇文章主要為大家介紹了ReactNative狀態(tài)管理rematch使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03