装饰器 和高阶函数HOC的理解

2,551 阅读1分钟

装饰器(Decorator) 是一个函数,用来修改组件或传入的类的行为,

** HOC **:一个函数接收一个组件作为参数,经过一系列加工之后,最后返回一个新的组件

装饰器的使用: 数据流传输:从上之下传输,children 可以拿到父级的方法时可以考虑使用装饰器

定义一个HOC的方法:

方法1:

// 简单的装饰器函数接收一个组件或者class 作为参数,经过加工处理后返回一个新的组件或者class函数
//component 就是传进去的class(装饰器需要装饰的class)
const simpleHoc = Component =>{
    return props => <Component {...props} />
}

方法2:

const simpleHoc = Comp => {
  return class extends Component {
    render() {
      return <Comp {...this.props}/>
    }
  }
}

定义装饰器的方法: 上述高阶组件也可以理解为一个装饰器

const testDecorator = target => {
    target.count = 1
}

@testDecorator
class MyTest {}

console.log(MyTest.count)   //  1

若要灵活使用 ,可在外层套一个函数,只要保证最后返回的是一个Decorator就可以

const testDecorator = params => {
    return (target)=>  target.count = params
}

@testDecorator(3)
class MyTest {}

console.log(MyTest.count)   //  3