新的context api使用了render props
:html
<ThemeContext.Consumer>
{theme => (
<button {...props} style={{backgroundColor: theme.background}} /> )} </ThemeContext.Consumer> 复制代码
第一次见到这个语法时,大多会很惊讶,由于平常代码里props.children
必然是字符串或者元素。但事实上props.children
能够是函数,只要最终生成的render的返回值是dom元素就行。例如:前端
// chilren props
const Test = props => props.children('hello world')
const App = () => (
<Test> {text => <div>{text}</div>} </Test>
)
ReactDOM.render((<App />, root) // 返回<div>hello world</div> 复制代码
虽然没有实际意义,但这便是一个 render props
。固然render props
最初的意思是:组件不本身定义render函数,而是经过一个名为render
的props
将外部定义的render函数传入使用。 以上例来讲,会是这样:react
// render props
const Test = props => props.render('hello world')
const App = () => (
<Test render={text => <div>{text}</div>} /> ) ReactDOM.render((<App />, root) // 返回<div>hello world</div> 复制代码
由于现实中render函数很庞大,为了代码整洁多半会使用children
而不是自定义的render
来接收外部的render函数。因此这一技巧也能够称为children props
(相对于render props
更加不知所云的名称),但通常统称render props
。git
为了重用性。React的组件化就是为了方便重用。大多数场景咱们须要重用的是UI(例如文章列表,侧栏),但也有少数状况须要重用的是功能和状态(例如context)。github
若是说React的核心是State => UI
, 普通的组件是UI重用,那么render props
就是为了State重用而应运而生的。spring
在 Demo 展开前插播一段 render props
的趣史。redux
import { Motion, spring } from 'react-motion';
<Motion defaultStyle={{x: 0}} style={{x: spring(10)}}> {value => <div>{value.x}</div>} </Motion>
复制代码
以后这一写法被各位大牛普遍接受,写过不少很是赞的前端教程的 Kent C. Dodds 就很是喜欢 render props, 他所任职的 PayPal 的输入框组件 downshift 也使用了 render propsapi
你们熟知的 react-router 的做者 Michael Jackson 也是 render props 的极力推崇者。他twitter过一句颇有争议的话:antd
Next time you think you need a HOC (higher-order component) in @reactjs, you probably don't.react-router
翻译过来就是:下次你想使用HOC解决问题时,其实大半不须要。 在回复中他补充说明到,
I can do anything you're doing with your HOC using a regular component with a render prop. Come fight me.
便是说,全部用 HOC 完成的事,render props 都能搞定。 值得一提的是 react-router 4
里惟一的一个 HOC 是withRouter
, 而它是用 render props 实现的,有兴趣的能够去看一下源代码。
fowardRef
就几乎是为此而生的),是个用着舒服写着烦的存在。因此感受最近大有“少写 HOC 推崇 render props”的思潮。至于新的 Context api 虽然思路上和react-redux
一模一样,却选择了 render props 的写法,在我看来也是瓜熟蒂落。实例1: 一个平常的使用场景是弹窗。App的弹窗UI可能千奇百怪,但它们的功能倒是相似的:无非有个显示隐藏的状态,和一个控制显隐的方法,以 antd 为例:
import { Modal, Button } from 'antd';
class App extends React.Component {
state = { visible: false }
showModal = () => {
this.setState({
visible: true,
});
}
handleOk = (e) => {
// 作点什么
this.setState({
visible: false,
});
}
handleCancel = (e) => {
this.setState({
visible: false,
});
}
render() {
return (
<div> <Button onClick={this.showModal}>Open</Button> <Modal title="Basic Modal" visible={this.state.visible} onOk={this.handleOk} onCancel={this.handleCancel} > <p>Some contents...</p> <p>Some contents...</p> <p>Some contents...</p> </Modal> </div>
);
}
}
复制代码
上面是最简单的Modal使用实例,但你们心中理想的使用方式是以下的:
<div>
<Button>Open</Button>
<Modal title="Basic Modal" onOk={this.handleOk //作点什么} >
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Modal>
</div>
复制代码
我只想写业务逻辑的 onOK
,其余部分不都是弹窗的实现细节吗,为啥不能封装起来?
答案是能够的。下面就使用 render props 来写一个Pop组件,封装全部逻辑。但愿的最终使用方式是:
<Pop>
{({ Button, Modal }) => (
<div>
<Button>Open</Button>
<Modal title="Simple" onOK={() => alert("everything is OK")}
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Modal>
</div>
)}
</Pop>
复制代码
你们能够先尝试本身写一下。我写的以下:
import { Modal, Button } from 'antd';
class Pop extends React.Component {
state = { on: false };
toggle = () => this.setState({ on: !this.state.on });
// 将antd 组件包裹上状态和方法
MyButton = props => <Button {...props} onClick={this.toggle} />;
MyModal = ({ onOK, ...rest }) => (
<Modal {...rest} visible={this.state.on} onOk={() => { onOK && onOK(); this.toggle(); }} onCancel={this.toggle} /> ); render() { return this.props.children({ on: this.state.on, toggle: this.toggle, Button: this.MyButton, Modal: this.MyModal }); } } 复制代码
简单的说,render props 将如何render组件的事代理给了使用它的组件,但同时以参数的形式提供了须要重用的状态和方法给外部。实现UI的自定义和功能的重用。不过这个例子有点激进,不只提供了状态和方法,还提供了带状态的组件做为参数。若是你们有不一样意见,请务必留言,互相学习。
实例2: 通常的render props只封装 “state”。React官方文档上 Dan Abromov 给出了一个很好的例子:鼠标跟踪的功能。这个功能有不少应用场景,也很好实现:
class Mouse extends React.Component {
state = { x: 0, y: 0 }
handleMouseMove = e =>
this.setState({ x: e.clientX, y: e.clientY })
render() {
return (
<div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}> <p>鼠标位于 ({this.state.x}, {this.state.y})</p> </div>
)
}
}
复制代码
但如何封装和重用这个功能呢?好比要写一个猫的图案跟着鼠标走。你们能够先试试。 答案以下:
// 封装
class Mouse extends React.Component {
state = { x: 0, y: 0 }
handleMouseMove = (e) =>
this.setState({ x: e.clientX, y: e.clientY })
render() {
return (
<div style={{ height: '100%' }} onMouseMove={this.handleMouseMove}> {this.props.children(this.state)} </div>
)
}
}
// 重用
const Cat = () =>
<Mouse>
{({x,y}) =>
<img src="/cat.jpg"
style={{ position: 'absolute', left: x, top: y }}
/>
}
<Mouse>
复制代码
若是太长没看的话,只有一句是我最想分享的:当你写项目时碰到须要重用的是功能不是UI时,试着用render props封装一个组件吧。固然 HOC 也是解决方法,不过关于 HOC vs render props 的讨论,下篇再写。