01-高阶组件HOC-认识

26 阅读1分钟

通过高阶函数-》高阶组件-》高阶组件的定义-〉应用场景 介绍 image.png

高阶函数

高阶函数,至少满足以下任意一个条件:

  • 返回一个函数
  • 接受函数作为参数
 foo1 (fn) {
    fn()
  }
  foo2 () {
    function bar () { }
    return bar
  }
  foo3 (fn1, fn2) {
      return {
          fun1(),
          fun2()
      }
  }

js中高阶函数

const arr = [1,2,3]
arr.map(item=> item * 2)
arr.filter(item => item > 2)
arr.find(item => item >2)
arr.reduce((pre, cur, index) => {return cur + pre}, 0)

react高阶组件

  1. 是一个函数
  2. 该函数接受一个组件
  3. 返回一个新组件

demo

import React, { PureComponent } from 'react'
// 定义一个高阶组件(函数)
function hoc (Cpn) {
  //定义类组件
  class newCpn extends PureComponent {
    render () {
      return (
        // <div>hahhhahh</div>
        <Cpn />
      )
    }
  }
  return newCpn
  // 定义函数组件
  // function newCpnFun (props) {

  // }
  // return newCpnFun
}
class HelloWorld extends PureComponent {
  render () {
    return (
      <div>
        hello world
      </div>
    )
  }
}
const HelloWorldHOC = hoc(HelloWorld)

export class App extends PureComponent {
  render () {
    return (
      <div>
        <HelloWorldHOC />
      </div>
    )
  }
}

export default App

高阶组件定义

image.png