任何一个项目发展到必定复杂性的时候,必然会面临逻辑复用的问题。在React
中实现逻辑复用一般有如下几种方式:Mixin
、高阶组件(HOC)
、修饰器(decorator)
、Render Props
、Hook
。本文主要就以上几种方式的优缺点做分析,帮助开发者针对业务场景做出更适合的方式。html
这或许是刚从Vue
转向React
的开发者第一个可以想到的方法。Mixin
一直被普遍用于各类面向对象的语言中,其做用是为单继承语言创造一种相似多重继承的效果。虽然如今React
已将其放弃中,但Mixin
的确曾是React
实现代码共享的一种设计模式。react
广义的 mixin 方法,就是用赋值的方式将 mixin 对象中的方法都挂载到原对象上,来实现对象的混入,相似 ES6 中的 Object.assign()的做用。原理以下:segmentfault
const mixin = function (obj, mixins) { const newObj = obj newObj.prototype = Object.create(obj.prototype) for (let prop in mixins) { // 遍历mixins的属性 if (mixins.hasOwnPrototype(prop)) { // 判断是否为mixin的自身属性 newObj.prototype[prop] = mixins[prop]; // 赋值 } } return newObj };
假设在咱们的项目中,多个组件都须要设置默认的name
属性,使用mixin
可使咱们没必要在不一样的组件里写多个一样的getDefaultProps
方法,咱们能够定义一个mixin
:设计模式
const DefaultNameMixin = { getDefaultProps: function () { return { name: "Joy" } } }
为了使用mixin
,须要在组件中加入mixins
属性,而后把咱们写好的mixin
包裹成一个数组,将它做为mixins
的属性值:api
const ComponentOne = React.createClass({ mixins: [DefaultNameMixin] render: function () { return <h2>Hello {this.props.name}</h2> } })
写好的mixin
能够在其余组件里重复使用。数组
因为mixins
属性值是一个数组,意味着咱们能够同一个组件里调用多个mixin
。在上述例子中稍做更改获得:antd
const DefaultFriendMixin = { getDefaultProps: function () { return { friend: "Yummy" } } } const ComponentOne = React.createClass({ mixins: [DefaultNameMixin, DefaultFriendMixin] render: function () { return ( <div> <h2>Hello {this.props.name}</h2> <h2>This is my friend {this.props.friend}</h2> </div> ) } })
咱们甚至能够在一个mixin
里包含其余的mixin
。react-router
好比写一个新的 mixin
`DefaultProps 包含以上的
DefaultNameMixin和
DefaultFriendMixin `:app
const DefaultPropsMixin = { mixins: [DefaultNameMixin, DefaultFriendMixin] } const ComponentOne = React.createClass({ mixins: [DefaultPropsMixin] render: function () { return ( <div> <h2>Hello {this.props.name}</h2> <h2>This is my friend {this.props.friend}</h2> </div> ) } })
至此,咱们能够总结出mixin
至少拥有如下优点:ide
mixin
;mixin
;mixin
里嵌套多个mixin
;可是在不一样场景下,优点也可能变成劣势:
state
和props
等状态;mixin
里的命名不可知,很是容易发生冲突;除此以外,mixin
在状态冲突、方法冲突、多个生命周期方法的调用顺序等问题拥有本身的处理逻辑。感兴趣的同窗能够参考一下如下文章:
因为mixin
存在上述缺陷,故React
剥离了mixin
,改用高阶组件
来取代它。
高阶组件
本质上是一个函数,它接受一个组件做为参数,返回一个新的组件。
React
官方在实现一些公共组件时,也用到了高阶组件
,好比react-router
中的withRouter
,以及Redux
中的connect
。在这以withRouter
为例。
默认状况下,必须是通过Route
路由匹配渲染的组件才存在this.props
、才拥有路由参数
、才能使用函数式导航
的写法执行this.props.history.push('/next')
跳转到对应路由的页面。高阶组件
中的withRouter
做用是将一个没有被Route
路由包裹的组件,包裹到Route
里面,从而将react-router
的三个对象history
、location
、match
放入到该组件的props
属性里,所以能实现函数式导航跳转
。
withRouter
的实现原理:
const withRouter = (Component) => { const displayName = `withRouter(${Component.displayName || Component.name})` const C = props => { const { wrappedComponentRef, ...remainingProps } = props return ( <RouterContext.Consumer> {context => { invariant( context, `You should not use <${displayName} /> outside a <Router>` ); return ( <Component {...remainingProps} {...context} ref={wrappedComponentRef} /> ) }} </RouterContext.Consumer> ) }
使用代码:
import React, { Component } from "react" import { withRouter } from "react-router" class TopHeader extends Component { render() { return ( <div> 导航栏 {/* 点击跳转login */} <button onClick={this.exit}>退出</button> </div> ) } exit = () => { // 通过withRouter高阶函数包裹,就可使用this.props进行跳转操做 this.props.history.push("/login") } } // 使用withRouter包裹组件,返回history,location等 export default withRouter(TopHeader)
因为高阶组件
的本质是获取组件而且返回新组件的方法
,因此理论上它也能够像mixin
同样实现多重嵌套。
例如:
写一个赋能唱歌的高阶函数
import React, { Component } from 'react' const widthSinging = WrappedComponent => { return class HOC extends Component { constructor () { super(...arguments) this.singing = this.singing.bind(this) } singing = () => { console.log('i am singing!') } render() { return <WrappedComponent /> } } }
写一个赋能跳舞的高阶函数
import React, { Component } from 'react' const widthDancing = WrappedComponent => { return class HOC extends Component { constructor () { super(...arguments) this.dancing = this.dancing.bind(this) } dancing = () => { console.log('i am dancing!') } render() { return <WrappedComponent /> } } }
使用以上高阶组件
import React, { Component } from "react" import { widthSing, widthDancing } from "hocs" class Joy extends Component { render() { return <div>Joy</div> } } // 给Joy赋能唱歌和跳舞的特长 export default widthSinging(withDancing(Joy))
由上可见,只需使用高阶函数进行简单的包裹,就能够把本来单纯的 Joy 变成一个既能唱歌又能跳舞的夜店小王子了!
在使用HOC
的时候,有一些墨守成规的约定:
render
函数中使用高阶组件(每次 render,高阶都返回新组件,影响 diff 性能);至此咱们能够总结一下高阶组件(HOC)
的优势:
HOC
是一个纯函数,便于使用和维护;HOC
是一个纯函数,支持传入多个参数,加强其适用范围;HOC
返回的是一个组件,可组合嵌套,灵活性强;固然HOC
也会存在一些问题:
HOC
嵌套使用时,没法直接判断子组件的props
是从哪一个HOC
负责传递的;props
,会致使父组件覆盖子组件同名props
的问题,且react
不会报错,开发者感知性低;HOC
都返回一个新组件,从而产生了不少无用组件,同时加深了组件层级,不便于排查问题;修饰器
和高阶组件
属于同一模式,在此不展开讨论。
Render Props
是一种很是灵活复用性很是高的模式,它能够把特定行为或功能封装成一个组件,提供给其余组件使用让其余组件拥有这样的能力。
The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.
这是React
官方对于Render Props
的定义,翻译成大白话即:“Render Props
是实现React Components
之间代码共享的一种技术,组件的props
里边包含有一个function
类型的属性,组件能够调用该props
属性来实现组件内部渲染逻辑”。
官方示例:
<DataProvider render={(data) => <h1>Hello {data.target}</h1>} />
如上,DataProvider
组件拥有一个叫作render
(也能够叫作其余名字)的props
属性,该属性是一个函数,而且这个函数返回了一个React Element
,在组件内部经过调用该函数来完成渲染,那么这个组件就用到了render props
技术。
读者或许会疑惑,“咱们为何须要调用props
属性来实现组件内部渲染,而不直接在组件内完成渲染”?借用React
官方的答复,render props
并不是每一个React
开发者须要去掌握的技能,甚至你或许永远都不会用到这个方法,但它的存在的确为开发者在思考组件代码共享的问题时,提供了多一种选择。
Render Props
使用场景咱们在项目开发中可能须要频繁的用到弹窗,弹窗 UI 能够变幻无穷,可是功能倒是相似的,即打开
和关闭
。以antd
为例:
import { Modal, Button } from "antd" class App extends React.Component { state = { visible: false } // 控制弹窗显示隐藏 toggleModal = (visible) => { this.setState({ visible }) }; handleOk = (e) => { // 作点什么 this.setState({ visible: false }) } render() { const { visible } = this.state return ( <div> <Button onClick={this.toggleModal.bind(this, true)}>Open</Button> <Modal title="Basic Modal" visible={visible} onOk={this.handleOk} onCancel={this.toggleModal.bind(this, false)} > <p>Some contents...</p> </Modal> </div> ) } }
以上是最简单的Model
使用实例,即使是简单的使用,咱们仍须要关注它的显示状态,实现它的切换方法。可是开发者其实只想关注与业务逻辑相关的onOk
,理想的使用方式应该是这样的:
<MyModal> <Button>Open</Button> <Modal title="Basic Modal" onOk={this.handleOk}> <p>Some contents...</p> </Modal> </MyModal>
能够经过render props
实现以上使用方式:
import { Modal, Button } from "antd" class MyModal extends React.Component { state = { on: false } toggle = () => { this.setState({ on: !this.state.on }) } renderButton = (props) => <Button {...props} onClick={this.toggle} /> renderModal = ({ onOK, ...rest }) => ( <Modal {...rest} visible={this.state.on} onOk={() => { onOK && onOK() this.toggle() }} onCancel={this.toggle} /> ) render() { return this.props.children({ Button: this.renderButton, Modal: this.renderModal }) } }
这样咱们就完成了一个具有状态和基础功能的Modal
,咱们在其余页面使用该Modal
时,只须要关注特定的业务逻辑便可。
以上能够看出,render props
是一个真正的React
组件,而不是像HOC
同样只是一个能够返回组件的函数,这也意味着使用render props
不会像HOC
同样产生组件层级嵌套的问题,也不用担忧props
命名冲突产生的覆盖问题。
render props
使用限制在render props
中应该避免使用箭头函数
,由于这会形成性能影响。
好比:
// 很差的示例 class MouseTracker extends React.Component { render() { return ( <Mouse render={mouse => ( <Cat mouse={mouse} /> )}/> ) } }
这样写是很差的,由于render
方法是有可能屡次渲染的,使用箭头函数
,会致使每次渲染的时候,传入render
的值都会不同,而实际上并无差异,这样会致使性能问题。
因此更好的写法应该是将传入render
里的函数定义为实例方法,这样即使咱们屡次渲染,可是绑定的始终是同一个函数。
// 好的示例 class MouseTracker extends React.Component { renderCat(mouse) { return <Cat mouse={mouse} /> } render() { return ( <Mouse render={this.renderTheCat} /> ) } }
render props
的优缺点优势
缺点
return
语句外访问数据;容易产生函数回调嵌套;
以下代码:
const MyComponent = () => { return ( <Mouse> {({ x, y }) => ( <Page> {({ x: pageX, y: pageY }) => ( <Connection> {({ api }) => { // yikes }} </Connection> )} </Page> )} </Mouse> ) }
React
的核心是组件,所以,React
一直致力于优化和完善声明组件的方式。从最先的类组件
,再到函数组件
,各有优缺点。类组件
能够给咱们提供一个完整的生命周期和状态(state),可是在写法上却十分笨重,而函数组件
虽然写法很是简洁轻便,但其限制是必须是纯函数,不能包含状态,也不支持生命周期,所以类组件
并不能取代函数组件
。
而React
团队以为组件的最佳写法应该是函数,而不是类,由此产生了React Hooks
。
React Hooks 的设计目的,就是增强版函数组件,彻底不使用"类",就能写出一个全功能的组件。
为何说类组件
“笨重”,借用React
官方的例子说明:
import React, { Component } from "react" export default class Button extends Component { constructor() { super() this.state = { buttonText: "Click me, please" } this.handleClick = this.handleClick.bind(this) } handleClick() { this.setState(() => { return { buttonText: "Thanks, been clicked!" } }) } render() { const { buttonText } = this.state return <button onClick={this.handleClick}>{buttonText}</button> } }
以上是一个简单的按钮组件,包含最基础的状态和点击方法,点击按钮后状态发生改变。
本是很简单的功能组件,可是却须要大量的代码去实现。因为函数组件
不包含状态,因此咱们并不能用函数组件
来声明一个具有如上功能的组件。可是咱们能够用Hook
来实现:
import React, { useState } from "react" export default function Button() { const [buttonText, setButtonText] = useState("Click me, please") function handleClick() { return setButtonText("Thanks, been clicked!") } return <button onClick={handleClick}>{buttonText}</button> }
相较而言,Hook
显得更轻量,在贴近函数组件
的同时,保留了本身的状态。
在上述例子中引入了第一个钩子useState()
,除此以外,React
官方还提供了useEffect()
、useContext()
、useReducer()
等钩子。具体钩子及其用法详情请见官方。
Hook
的灵活之处还在于,除了官方提供的基础钩子以外,咱们还能够利用这些基础钩子来封装和自定义钩子,从而实现更容易的代码复用。
优势
缺点
useEffect
hook
除了Mixin
由于自身的明显缺陷而稍显落后以外,对于高阶组件
、render props
、react hook
而言,并无哪一种方式可称为最佳方案
,它们都是优点与劣势并存的。哪怕是最为最热门的react hook
,虽然每个hook
看起来都是那么的简短和清爽,可是在实际业务中,一般都是一个业务功能对应多个hook
,这就意味着当业务改变时,须要去维护多个hook
的变动,相对于维护一个class
而言,心智负担或许要增长许多。只有切合自身业务的方式,才是最佳方案
。
参考文档:
欢迎关注凹凸实验室博客:aotu.io
或者关注凹凸实验室公众号(AOTULabs),不定时推送文章。