简单写一个hoc

hoc类似vue里的mixins,可以将一些公用逻辑写成hoc,但凡使用这个hoc的组件都具有这些逻辑

1、不带参

import React, { Component } from 'react'

const Hoc = WrappedComponent => {
    class NewComponent extends Component {
        componentDidMount() {
            console.log('触发了高阶组件的mount')
        }
        render() {
            return <WrappedComponent {...this.props} />
        }
    }
    return NewComponent
}

export default Hoc

使用:

Hoc(你的组件)

// 若你的组件是class组件,还可用装饰器@
@Hoc
class YourComponent extends Component {}

2、带参

import React, { Component } from 'react'

// 这里参数是先接收数据再接收组件
const Hoc = params => WrappedComponent => {
    class NewComponent extends Component {
        render() {
            return <WrappedComponent {...this.props} {...params} />
        }
    }
    return NewComponent
}

export default Hoc

使用:

Hoc({a: 1, b: 2})(你的组件) // 注意数据在前,组件在后,因为我们Hoc里这样定义的

// 若你的组件是class组件,可用装饰器@
@Hoc({a: 1, b: 2})
class YourComponent extends Component {}

上面的Hoc只是基本架子,具体根据实际业务去写,一般来说是封装公用钩子处理、传递公用参数或方法。

猜你喜欢

转载自blog.csdn.net/qq_43119912/article/details/127849833