如何将 HOC 与 class 组件一起使用

How to use a HOC with a class Component

我花了最后几个小时研究如何渲染它,但我无法理解它。

const Test = props => (
  <p>
    {console.log(props)}
    {props.children}
  </p>
)

const changeColor = WrappedComponent => props => {
  return class extends React.Component {
    render() {
      return (
        <WrappedComponent style={{ color: props.color }} test="adasd">
          {props.children}
        </WrappedComponent>
      )
    }
  }
}

const Temp = changeColor(Test)

当我去渲染它时,它告诉我 Functions are not valid as a React child. 我将如何 return 一个 Class 组件,因为我需要访问状态。

那是因为 changeColor

function that return function that returns class component

要使您的代码正常工作,您需要:

const props = {};

const Temp = changeColor(Test)(props)

但是,我认为你不需要那个以 props 作为参数的函数:

const changeColor = WrappedComponent => {
  return class extends React.Component {
    render() {
      return (
        <WrappedComponent style={{ color: this.props.color }} test="adasd">
          {this.props.children}
        </WrappedComponent>
      )
    }
  }
}

const Temp = changeColor(Test)