首先打个广告,系列文章: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