"Render Props"是指一種在 React 組件之間使用一個值為函數(shù)的 prop 共享代碼的簡單技術(shù)。
具有 render prop 的組件接受一個函數(shù),該函數(shù)返回一個 React 元素并調(diào)用它而不是實現(xiàn)自己的渲染邏輯。
<DataProvider render={data => (
<h1>Hello {data.target}</h1>
)}/>
是不是很簡單,更具體地說,render prop 是一個用于告知組件需要渲染什么內(nèi)容的函數(shù) prop。
照例,卷起袖子擼代碼~~~
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 style={{ height: "100%" }} onMouseMove={this.handleMouseMove}>
{/* ...但我們?nèi)绾武秩?<p> 以外的東西? */}
<p>
The current mouse position is ({this.state.x}, {this.state.y})
</p>
{this.props.render(this.state)}
</div>
);
}
}
class MouseTracker extends React.Component {
render() {
return (
<div style={{ height: "100vh", backgroundColor: "#676767" }}>
<h1>移動鼠標(biāo)!</h1>
<Mouse
render={mouse => {
if (mouse.x > 500 && mouse.y > 500) {
return <Dog mouse={mouse} />;
} else {
return <Cat mouse={mouse} />;
}
}}
/>
</div>
);
}
}
class App extends React.Component {
render() {
return (
<div>
<MouseTracker />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));

實例中,我們在
<Mouse>中監(jiān)聽光標(biāo)在屏幕上移動,獲取其位置。然后將<Cat> 組件(還有<Dog> 組件)也顯示到光標(biāo)的位置。
以往做法,
可以嘗試在<Mouse> 內(nèi)部的直接渲染<Cat>組件,采用組合組件的方式實現(xiàn);
也可以采用HOC(高階組件)的方式實現(xiàn)。但是這些方式都得創(chuàng)建組件。
如果采用render prop 可以輕松解決。
我們提供了一個 render 方法 讓 <Mouse> 能夠動態(tài)決定什么需要渲染,而不是克隆 <Mouse> 組件然后硬編碼來解決特定的用例。這種實現(xiàn)方式比嘗試在 <Mouse> 內(nèi)部的渲染方法渲染 <Cat> 組件要方便的多,不用每次都得創(chuàng)建新的組件。
驚喜
關(guān)于 render prop 一個有趣的事情是你可以使用帶有 render prop 的常規(guī)組件來實現(xiàn)大多數(shù)高階組件 (HOC)。 例如,如果你更喜歡使用 HOC而不是組合組件,你可以使用帶有 render prop 的常規(guī) <Mouse> 輕松創(chuàng)建一個:
// 如果你出于某種原因真的想要 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} />
)}/>
);
}
}
}
注意點
使用 Props 而非 render
重要的是要記住,render prop 是因為模式才被稱為 render prop ,你不一定要用名為 render的 prop 來使用這種模式。事實上, 任何被用于告知組件需要渲染什么內(nèi)容的函數(shù) prop 在技術(shù)上都可以被稱為 “render prop”.
盡管之前的例子使用了 render,我們也可以簡單地使用 children prop!
<Mouse children={mouse => (
<p>鼠標(biāo)的位置是 {mouse.x},{mouse.y}</p>
)}/>
其他的注意事項可以去官網(wǎng)看看細節(jié),這邊就不累贅了(這里的基本夠用,但是細節(jié)不足,翻閱官網(wǎng)資料就當(dāng)多看一遍加深印象吧!)
Render Props直通車