首页 > 解决方案 > 如何将属性从有状态组件传递到包装子组件的 HOC 中使用的事件处理程序?

问题描述

我正在使用一个框架,我必须将一个事件处理程序传递给一个 HOC,该 HOC 包装了我的有状态 Page 组件的一个子组件。

<Page>
    <HOC onClick={fn}>
        <PageColumn>
        </PageColumn>
    </HOC>
</Page>

我的有状态页面组件中有一个函数,它依赖于页面的状态和道具。我必须使用包装页面子组件的 HOC。在这个 HOC 中,我必须调用一个依赖于 Page 组件状态的 onClick 方法。

到目前为止,我已经尝试传递对 this.state 的引用以便在 HOC 中使用 Page 状态,并且我已经尝试传递在父状态中分配了我需要的值的道具。在 onClick fn 中,无论我是使用 this.state 还是 this.props 引用必要的属性,我都会收到错误消息:

 cannot read property '<attribute>' of undefined

我怎样才能成功地实现这种模式?

标签: javascriptreactjshigher-order-components

解决方案


您的代码没有太多需要调查的地方。我注意到您使用 HOC 作为组件,但通常 hoc 是向组件添加某些内容的函数。

通常 hoc 是这样工作的:

EnrichedComponent = hoc(options)(BaseComponent);

示例:react-redux connecthoc 函数

这种方法应该有效:

// render Page somewhere
const App = () => (
  <Page/>
)

// let Page component render the PageColumn component
class Page extends React.Component {
  handleClick() {
    // I can access page state and props
    const {
      state: { foo },
      props: { bar },
    } = this;

    console.log(foo, bar);
  }

  render() {
    return (
      <PageColumn onClick={this.handleClick} />
    )
  }
}

// wrap component with HOC
const PageColumn = hoc()(() => {
  return (
    <div>...</div>
  )
});

推荐阅读