【发布时间】:2017-08-28 19:52:27
【问题描述】:
给定一个标准的 compose 函数和一个 'div' 组件,你将如何编写这两个 HOC:
- “div”元素一开始是一个 20 像素的绿色框,然后点击后变成一个 50 像素的蓝色框。
- 关注点 - a:将状态与 props 合并,b:触发状态更改,由单独的 HOC 处理。
- 更新程序 HOC 将状态映射到 props,并设置默认状态
- 调度程序 HOC 接受一个函数以在单击时获取新状态
下面的示例用于获取一个绿色框,并正确触发处理程序。更新仅在 Dispatcher HOC 的状态下发生。 updater HOC 的状态保持不变,它的 props 也是如此。
我真的很想知道发生了什么。在 compose 中翻转两个 HOC 的顺序会导致无法设置处理程序。由于它们都合并在{...this.props} 中,这对我来说没有意义。猜猜我不明白多个 HOC 如何合并 props 和 state。
const HOCDispatcher = myFunc => BaseComponent => {
return class Dispatcher extends React.Component {
constructor(props,context){
super(props,context);
this.handlerFn = (event)=>{this.setState(myFunc)}
}
render(){
return createElement(BaseComponent,{...this.props,onClick:this.handlerFn});
}
}
}
const HOCUpdater = defaultState => BaseComponent => {
return class Updater extends React.Component {
constructor(props,context){
super(props,context);
this.state = Object.assign({},defaultState,this.state);
}
render(){
return createElement(BaseComponent,{...this.props,...this.state});
}
}
}
const MyComponent = compose(
HOCDispatcher(()=>({
style:{width:'50px',height:'50px',background:'blue'}
})),
HOCUpdater({
style:{width:'20px',height:'20px',background:'green'}
}),
)('div');
【问题讨论】:
标签: reactjs higher-order-components