了解render props之前先來回顧一下之前學習過的高階組件HOC,高階組件是接收一個組件作為參數(shù)须板,返回一個新的組件撕予。其作用就是提高組件的復用性。今天學習的render props也是為了簡化代碼做裙,提高組件復用性岗憋。
render props 組件接收一個函數(shù),該函數(shù)會調(diào)用另一個組件而不是直接渲染锚贱, 有一點我們需要注意仔戈,一般一個組件調(diào)用另一個組件,是將被調(diào)用的組件渲染到該組件中拧廊,然后進行硬編碼监徘,而render props是接收函數(shù),直接調(diào)用函數(shù)吧碾,其函數(shù)輸出結(jié)果作為 props 傳入主組件凰盔。
render props的一般格式是:
<CustomerComponent render={ data=> (
? ? ? ? <h1>Hello {data.target}
)} />
這里用官方文檔中的例子簡單說明。 獲取鼠標當前位置倦春,我們可以定義一個組件
class Cat extends React.Component {
? ? render() {
? ? ? ? const mouse = this.props.mouse;
? ? ? ? renturn (
? ? ? ? ? ? <img? style={{ left: mouse.x, top, mouse.y}}
}
class Mouse extends React.Component {
? ? ? ? constructor(props) {
? ? ? ? ? ? ? ? super(props)
? ? ? ? ? ? ? ? this.handleMouseMove = this.handleMouseMove.bind(this)
? ? ? ? ? ? ? ? this.state = {x:0, y:0}
? ? ? ? handleMouseMove(event) {
? ? ? ? ? ? ? ? this.setState(
? ? ? ? ? ? ? ? ? ? x:event.clientX,
? ? ? ? ? ? ? ? ? ? y: event.clientY
? ? ? ? ? ? ? ? )
? ? ? ? }
? ? ? ? render() {
? ? ? ? ? ? ? ? return (????
? ? ? ? ? ? ? ? ? ? <div onMouseMove={this.handleMouseMove}>?
? ? ? ? ? ? ? ? ? ? ? ? {this.props.render(this.state)}
? ? ? ? ? ? ? ? ? ? ? ? //原本應該直接輸出 <p>鼠標的位置為: x: { this.state.x } ; y: { this.state.y }
? ? ? ? ? ? ? ? ? ? </div>
? ? ? ? ? ? ? ? );
? ? ? ? ? }
}
class MouseTracker extends React.Component {? ?
????????render() { ????
????????????????return (?
????????????????????????<div>?
????????????????????????????<h1>移動鼠標!</h1>
????????????????????????????<Mouse render={mouse => ( <Cat mouse={mouse} /> )}/>?
????????????????? ? ? </div>?
????????????????);
????????}
}?
上面這個例子的效果是想渲染一個追著鼠標的貓咪的效果户敬。 可以看到MouseTracker組件中調(diào)用了獲取鼠標位置的組件Mouse, 而Mouse組件中使用了 render props ,傳入了一個函數(shù)溅漾, Mouse組件內(nèi)部是捕獲了這個 render props? “{this.props.render(this.state)}” 將 this.state 的值綁定到 Mouse 的 mouse參數(shù)中山叮, mouse 參數(shù)又通過調(diào)用 <Cat mouse={mouse} /> 作為 props 參數(shù)傳入到 Cat組件中。所以 Cat組件中用了 const mouse= this.props.mouse; 來捕獲該值添履。?
開頭我們簡單提到 高階組件HOC屁倔,這里再貼一個 HOC 結(jié)合 render props的方法,實現(xiàn)上面代碼相同的功能暮胧。
// 如果你出于某種原因真的想要 HOC锐借,那么你可以輕松實現(xiàn)
// 使用具有 render prop 的普通組件創(chuàng)建一個!
function withMouse(Component) {
????return class extends React.Component {
????????render() {
????????????return (?
????????????????<Mouse render={mouse => ( <Component {...this.props} mouse={mouse} /> )}/>
????????????);
????????}
????}
}