定义

为了给一个函数赋能,增强它的某种能力,可以动态的添加对象的行为

场景

给已定义好的函数或组件添加新能力

React的高阶组件HOC

用高阶组件HOC来装饰Target Component

  1. import React from 'react'
  2. const yellowHOC = WrapperComponent => {
  3. return class extends React.Component {
  4. render() {
  5. <div style={{ backgroundColor: 'yellow' }}>
  6. <WrapperComponent {...this.props} />
  7. </div>
  8. }
  9. }
  10. }
  11. export default yellowHOC
  1. import React from 'react'
  2. import yellowHOC from './yellowHOC'
  3. // 定义一个带有装饰黄色背景的高阶组件,用它来装饰目标组件
  4. class TargetComponent extends React.Compoment {
  5. render() {
  6. return <div>66666</div>
  7. }
  8. }
  9. export default yellowHOC(TargetComponent)

能力扩展

  1. const kuanWrite = function() {
  2. this.writeChinese = function() {
  3. console.log('我只会写中文')
  4. }
  5. }
  6. // 通过装饰器给阿宽加上写英文的能力
  7. const Decorator = function(old) {
  8. this.oldWrite = old.writeChinese
  9. this.writeEnglish = function() {
  10. console.log('给阿宽赋予写英文的能力')
  11. }
  12. this.newWrite = function() {
  13. this.oldWrite()
  14. this.writeEnglish()
  15. }
  16. }
  17. const oldKuanWrite = new kuanWrite()
  18. const decorator = new Decorator(oldKuanWrite)
  19. decorator.newWrite()

输出

  1. 我只会写中文
  2. 给阿宽赋予写英文的能力