javascript - 如何将属性从有状态组件传递到包装子组件的 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
我怎样才能成功地实现这种模式?
解决方案
您的代码没有太多需要调查的地方。我注意到您使用 HOC 作为组件,但通常 hoc 是向组件添加某些内容的函数。
通常 hoc 是这样工作的:
EnrichedComponent = hoc(options)(BaseComponent);
示例:react-redux connect
hoc 函数
这种方法应该有效:
// 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>
)
});
推荐阅读
- c# - 使用c#从字符串中删除转义字符
- javascript - Ember 快速入门教程:解析错误:“@action”中出现意外字符“@”
- list - 如何永远在列表中追加一个元素?
- python - 在 PyQt5 中创建小部件时使用 self 有什么意义
- javascript - 如何获取数组中的每个第n个数字?不行
- java - 使用集合处理 Gson 中的类型检查
- reactjs - 在 redux saga 中使用和不使用 call 方法有什么区别?
- android - Android中的什么pathPrefix使整个域成为深度链接?
- javascript - NodeJS中的字符串操作
- java - 始终找不到第一个模式键