如何将类HOC转换为功能性HOC?

时间:2020-09-09 12:09:00

标签: reactjs

我已经使用基于withProvider的组件实现了HOC class

import React from "react"
import Context from "./context"

const WithProvider = Component => {
    class WithContext extends React.Component {
        constructor(props) {
            super(props);
        }
        render() {
            return <Context.Provider value={{ type: this.props.type }} >
                <Component {...this.props} />
            </Context.Provider>
        }
    }
    return WithContext
}

export default WithProvider

但是代码库中的所有组件都是基于功能的。

因此,我想将withContext转换为Functional

1 个答案:

答案 0 :(得分:2)

HOC的功能形式如下:

const withFoo = (Component) => {
  return (props) => {
    return <Component foo={'foo!'} {...props} />
  };
}

const Bar = withFoo((props) => {
  return <div>hello: {props.foo} bar: {props.bar}</div>
})

您可以根据自己的需要轻松暗示此示例。