【问题标题】:How to use a HOC with a class Component如何将 HOC 与类组件一起使用
【发布时间】:2018-04-17 07:53:45
【问题描述】:

过去几个小时我一直在研究如何渲染它,但我无法理解它。

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. 我将如何返回一个类组件,因为我需要访问状态。

【问题讨论】:

  • 我认为你不能渲染console.log
  • @Andrew 感谢您的回复。如果我这样做const Var = Temp("test") 然后我得到它来渲染。这是否意味着我总是必须两次调用该函数,即Temp &amp;&amp; Var 确实要渲染类组件?如果是这样,那似乎有点太多了。

标签: reactjs higher-order-components


【解决方案1】:

那是因为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)

【讨论】:

  • 你真的救了我!我花了更多的时间来承认这一点!只是为了确认一下,HOC,他们没有返回 new 组件,而是他们只是改变了你传入的那个?
  • @StrahinjaAjvaz,HOC 确实返回了一个新组件
  • @StrahinjaAjvaz HOC 是一个返回组件的函数。而已。但 HOC 或多或少让您能够重用 javascript 范围和配置传递的组件。
  • 问题,为什么我们不能为 HOC 使用功能组件。我的意思是这个类什么都不做,只是渲染,我们不使用它的状态
  • @akshaykishore 好问题。我认为您可以使用功能组件。现在有了钩子就更容易了
猜你喜欢
  • 2019-06-18
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 2020-05-22
  • 2021-10-02
  • 2021-05-22
相关资源
最近更新 更多