【问题标题】:Trouble understanding how props are accessed in HOC无法理解如何在 HOC 中访问道具
【发布时间】:2018-12-21 04:55:28
【问题描述】:

我正在尝试理解这个 HOC 的基本示例:

function ppHOC(WrappedComponent) {

 return class PP extends React.Component {

    constructor(props) {
      super(props)
      this.state = {
        name: ''
      }

    this.onNameChange = this.onNameChange.bind(this)
 }

 onNameChange(event) {
  this.setState({
    name: event.target.value
  })
 }

 render() {
  const newProps = {
    name: {
      value: this.state.name,
      onChange: this.onNameChange
    }
  }
  return <WrappedComponent {...this.props} {...newProps}/>
 }
}

让我烦恼的是在 return 语句中使用 this.props :

return <WrappedComponent {...this.props} {...newProps}/>

据我了解,“this”指的是 PP 的实例?所以我们用 PP 的 props 实例化 WrappedComponent,它们是 React.Component 的 props,对吗?我确实了解我们也将 newProps 添加到这些道具中,但我只是不明白我们在这里使用 this.props 做什么。

PP 的构造函数也获取了一些 props 作为参数。 PP到底是如何实例化的? ppHOC(MyComponent) 返回的类 PP 不是它的一个实例,对吗?为了实例化 PP,您必须执行“ppHOC(MyComponent)(someProps)”之类的操作?

【问题讨论】:

    标签: reactjs wrapper react-props high-order-component


    【解决方案1】:

    据我了解,“this”指的是 PP 的实例?

    是的,没错

    所以我们用 PP 的 props 实例化 WrappedComponent,PP 的 props 是 React.Component 的 props,对吗?

    差不多了,这样想吧,这是你在 HOC 之前的反应结构: Parent component passes `props` to Child component

    现在你用 HOC 包裹你的孩子 (ppHOC(Child)) 你的结构变成: Parent component passes `props` to the component returned from `ppHOC(Child)`, which is class PP

    PP 的构造函数也获取了一些 props 作为参数。 PP究竟是如何实例化的? ppHOC(MyComponent) 返回的类 PP 不是它的一个实例,对吗?为了实例化 PP,您必须执行“ppHOC(MyComponent)(someProps)”之类的操作?

    确实ppHOC(MyComponent) returns the class PP,当你开始使用&lt;MyComponentHOC some="prop" /&gt;时,它会被React发起(渲染)。

    现在已启动 PP,{ some: "prop" } 将在 PP 的 constructor(props) 中传递,然后依次通过 (...this.props) 传递到您的 WrappedComponent

    简而言之{...this.props} 是将它(HOC)收到的任何道具传递给被包装的组件

    【讨论】:

    • 感谢您提供详细信息。这很好地回答了我的所有问题。
    猜你喜欢
    • 2020-02-05
    • 2021-04-12
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多