首先打個廣告,系列文章:react
下面進入正題:數組
A render prop is a function prop that a component uses to know what to render.bash
Render Props 的核心思想是,經過一個函數將class組件的state做爲props傳遞給純函數組件。這句話理解起來比較拗口。其實不管是上上篇文章中的React mixins仍是上篇文章中的React HOC都是在解決代碼複用問題,Render Props也不無例外。 咱們接着來用上篇文章中的🌰。dom
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
class Mouse extends React.Component {
static propTypes = {
render: PropTypes.func.isRequired,
}
state = { x: 0, y: 0 }
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
});
}
render() {
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
)
}
}
// APP是一個純函數無狀態組件
const App = () => (
<div style={{ height: '100%' }}>
<Mouse render={({ x, y }) => (
<h1>The mouse position is ({x}, {y})</h1>
)}/>
</div>
)
ReactDOM.render(<App/>, document.getElementById('root'))
複製代碼
組件其實是調用了父組件的 render 方法來將它的 state 暴露給 組件。所以, 能夠隨便按本身的想法使用這個 state,這太美妙了。函數
從demo中很容易看到,新建的Mouse組件的render方法中返回了{this.props.render(this.state)}這個函數,將其state做爲參數傳入其的props.render方法中,調用時直接取組件所須要的state便可。ui