
一、概念
renderProps是另外一个能实现类似于HOC这种多个组件抽离公共组件逻辑的方式。
二、例子

import React from 'react'
import PropTypes from 'prop-types'
class Mouse extends React.Component {
constructor(props) {
super(props)
this.state = { x: 0, y: 0 }
}
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
})
}
render() {
return (
<div style={{ height: '500px' }} onMouseMove={this.handleMouseMove}>
{/* 将当前 state 作为 props ,传递给 render (render 是一个函数组件) */}
{this.props.render(this.state)}
</div>
)
}
}
Mouse.propTypes = {
render: PropTypes.func.isRequired // 必须接收一个 render 属性,而且是函数
}
const App = (props) => (
<div style={{ height: '500px', background:'orange' }}>
<p>{props.a}</p>
<Mouse render={
/* render 是一个函数组件 */
({ x, y }) => <h1>The mouse position is ({x}, {y})</h1>
}/>
</div>
)
/**
* 即,定义了 Mouse 组件,只有获取 x y 的能力。
* 至于 Mouse 组件如何渲染,App 说了算,通过 render prop 的方式告诉 Mouse 。
*/
export default App
三、HOC vs RenderProps
- HOC:模式简单,但会增加组件层级,相应增加透传成本
- RenderProps: 代码简洁,学习成本高
- 按需使用




![在调试器下看微信[如何耗电]](https://img-blog.csdnimg.cn/img_convert/a873e043a2f2ecba787f5c5f2c8422a9.jpeg)
![[SQL | MyBatis] MyBatis 简介](https://img-blog.csdnimg.cn/b8551321cd504535bbc61a2e3f5c4234.png)










![堆/二叉堆详解[C/C++]](https://img-blog.csdnimg.cn/4f07332950684248bc22b83333581e33.gif#pic_center)


