任何一个我的项目倒退到肯定复杂性的时候,必然会面临逻辑复用的问题。在React
中实现逻辑复用通常有以下几种形式:Mixin
、高阶组件(HOC)
、润饰器(decorator)
、Render Props
、Hook
。本文次要就以上几种形式的优缺点作剖析,帮忙开发者针对业务场景作出更适宜的形式。
Mixin
这或者是刚从Vue
转向React
的开发者第一个可能想到的办法。Mixin
始终被宽泛用于各种面向对象的语言中,其作用是为单继承语言发明一种相似多重继承的成果。尽管当初React
已将其放弃中,但Mixin
确实曾是React
实现代码共享的一种设计模式。
狭义的 mixin 办法,就是用赋值的形式将 mixin 对象中的办法都挂载到原对象上,来实现对象的混入,相似 ES6 中的 Object.assign()的作用。原理如下:
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
};
在 React 中应用 Mixin
假如在咱们的我的项目中,多个组件都须要设置默认的name
属性,应用mixin
能够使咱们不用在不同的组件里写多个同样的getDefaultProps
办法,咱们能够定义一个mixin
:
const DefaultNameMixin = {
getDefaultProps: function () {
return {
name: "Joy"
}
}
}
为了应用mixin
,须要在组件中退出mixins
属性,而后把咱们写好的mixin
包裹成一个数组,将它作为mixins
的属性值:
const ComponentOne = React.createClass({
mixins: [DefaultNameMixin]
render: function () {
return <h2>Hello {this.props.name}</h2>
}
})
写好的mixin
能够在其余组件里重复使用。
因为mixins
属性值是一个数组,意味着咱们能够同一个组件里调用多个mixin
。在上述例子中稍作更改失去:
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
。
比方写一个新的 mixin
`DefaultProps 蕴含以上的
DefaultNameMixin和
DefaultFriendMixin `:
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
至多领有以下劣势:
- 能够在多个组件里应用雷同的
mixin
; - 能够在同一个组件里应用多个
mixin
; - 能够在同一个
mixin
里嵌套多个mixin
;
然而在不同场景下,劣势也可能变成劣势:
- 毁坏原有组件的封装,可能须要去保护新的
state
和props
等状态; - 不同
mixin
里的命名不可知,非常容易发生冲突; - 可能产生递归调用问题,减少了我的项目复杂性和保护难度;
除此之外,mixin
在状态抵触、办法抵触、多个生命周期办法的调用程序等问题领有本人的解决逻辑。感兴趣的同学能够参考一下以下文章:
- React Mixin 的应用
- Mixins Considered Harmful
高阶组件
因为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 的约定
在应用HOC
的时候,有一些按部就班的约定:
- 将不相干的 Props 传递给包装组件(传递与其具体内容无关的 props);
- 分步组合(防止不同模式的 HOC 串联调用);
- 蕴含显示的 displayName 不便调试(每个 HOC 都应该合乎规定的显示名称);
- 不要在
render
函数中应用高阶组件(每次 render,高阶都返回新组件,影响 diff 性能); - 静态方法必须被拷贝(通过高阶返回的新组件,并不会蕴含原始组件的静态方法);
- 防止应用 ref(ref 不会被传递);
HOC 的优缺点
至此咱们能够总结一下高阶组件(HOC)
的长处:
HOC
是一个纯函数,便于应用和保护;- 同样因为
HOC
是一个纯函数,反对传入多个参数,加强其适用范围; HOC
返回的是一个组件,可组合嵌套,灵活性强;
当然HOC
也会存在一些问题:
- 当多个
HOC
嵌套应用时,无奈直接判断子组件的props
是从哪个HOC
负责传递的; - 当父子组件有同名
props
,会导致父组件笼罩子组件同名props
的问题,且react
不会报错,开发者感知性低; - 每一个
HOC
都返回一个新组件,从而产生了很多无用组件,同时加深了组件层级,不便于排查问题;
润饰器
和高阶组件
属于同一模式,在此不展开讨论。
Render Props
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
的优缺点
-
长处
- props 命名可批改,不存在互相笼罩;
- 分明 props 起源;
- 不会呈现组件多层嵌套;
-
毛病
- 写法繁琐;
- 无奈在
return
语句外拜访数据; -
容易产生函数回调嵌套;
如下代码:
const MyComponent = () => { return ( <Mouse> {({ x, y }) => ( <Page> {({ x: pageX, y: pageY }) => ( <Connection> {({ api }) => { // yikes }} </Connection> )} </Page> )} </Mouse> ) }
Hook
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
的灵便之处还在于,除了官网提供的根底钩子之外,咱们还能够利用这些根底钩子来封装和自定义钩子,从而实现更容易的代码复用。
Hook 优缺点
-
长处
- 更容易复用代码;
- 清新的代码格调;
- 代码量更少;
-
毛病
- 状态不同步(函数独立运行,每个函数都有一份独立的作用域)
- 须要更正当的应用
useEffect
- 颗粒度小,对于简单逻辑须要形象出很多
hook
总结
除了Mixin
因为本身的显著缺点而稍显落后之外,对于高阶组件
、render props
、react hook
而言,并没有哪种形式可称为最佳计划
,它们都是劣势与劣势并存的。哪怕是最为最热门的react hook
,尽管每一个hook
看起来都是那么的简短和清新,然而在理论业务中,通常都是一个业务性能对应多个hook
,这就意味着当业务扭转时,须要去保护多个hook
的变更,绝对于保护一个class
而言,心智累赘或者要减少许多。只有切合本身业务的形式,才是最佳计划
。
参考文档:
- React Mixin 的应用
- Mixins Considered Harmful
- Higher-Order Components
- Render Props
- React 拾遗:Render Props 及其应用场景
- Hook 简介
欢送关注凹凸实验室博客:aotu.io
或者关注凹凸实验室公众号(AOTULabs),不定时推送文章。
发表回复