react 高阶组件HOC学习

161 阅读1分钟

一句话高阶组件:高阶组件是一个函数,接收一个组件作为参数,经过函数的加工增加一些功能返回一个新的组件。 demo如下:

HOC.jsx
import React from 'react';

export function MyHoc(WrappedComponent: any) {
  return class extends React.Component {
    constructor(props: any) {
      super(props);
      this.state = {
        test: 'this is my Hoc !'
      }
      this.changeValue = this.changeValue.bind(this)
    }

    componentDidMount () {
      console.log('HOC初始化!')
    }

    componentDidUpdate () {
      console.log('MyHoc!');
    }

    changeValue = () => {
      console.log(Math.random() * 10000);
      this.setState({
        test: Math.random() * 10000
      })
    }

    render () {
      return < WrappedComponent state={this.state} changeValue={this.changeValue} {...this.props} />
    }
  }
}

使用这个HOC:

testPages.jsx:

import React, { Component } from 'react';
import { MyHoc } from '../../components/Hoc1';

class MyHocTest2 extends Component {
    render () {
        return (
            <div>
                <button onClick={() => {this.props.test('12312312')}}>高阶组件复用</button>
                { this.props.state.count }
            </div>
        )
    }
}

class MyHocTest3 extends Component {
    render () {
        return (
            <div>
                <button onClick={() => {this.props.changeValue()}}>这是我的HOC!</button>
                { this.props.state.test }
            </div>
        )
    }
}


const EnhanceC = logProps(MyHocTest2)

const MyHoc1 = MyHoc(MyHocTest3)

class HocComponent extends Component {
    render () {
        return (
            <div id='root' >
                <EnhanceC />
                <EnhanceC2 />
                <MyHoc1 />
            </div>
        );
    }
}

export default HocComponent