- Hands-On Design Patterns with React Native
- Mateusz Grzesiukiewicz
- 180字
- 2021-08-13 15:12:57
HOC composition
The primary reason to create HOCs it to have the ability to compose the features they provide.
Look at the problem from the previous section again. What if we could delegate work to another HOC? For instance, having a mapper HOC called mapPropNames, you can compose it with our previous HOC like this:
makeExpandable(mapPropNames(SomeSection));
Here is the implementation of mapPropNames:
// src/ Chapter_1/ Example_15_HOC_Composition/ App.js
const mapPropNames = (Component) => (props) => (
<Component
{...props}
isVisible={props.isExpanded}
showHideBox={props.expandOrCollapse}
/>
);
Nice and quick, isn't it? This is a common pattern and is also used when working with backend data sent as JSON. It may adapt the data format to our representation on the frontend layer. As you see, we can employ this great idea when working with HOCs as well!
If you come from an object-oriented background, please notice that the HOC pattern is very similar to the decorator pattern. The decorator, however, also relies on inheritance and needs to implement the interface that it decorates.
Please check https://en.wikipedia.org/wiki/Decorator_pattern for examples.
You can also compose decorators. It works in a similar way.
Please check https://en.wikipedia.org/wiki/Decorator_pattern for examples.
You can also compose decorators. It works in a similar way.
推薦閱讀
- UML和模式應用(原書第3版)
- R語言經典實例(原書第2版)
- 算法零基礎一本通(Python版)
- Python數據分析基礎
- Java Web開發之道
- Python網絡爬蟲從入門到實踐(第2版)
- Learn Swift by Building Applications
- Visual C++串口通信技術詳解(第2版)
- SSM開發實戰教程(Spring+Spring MVC+MyBatis)
- 區塊鏈架構之美:從比特幣、以太坊、超級賬本看區塊鏈架構設計
- 大學計算機基礎實驗指導
- PHP+MySQL動態網站開發從入門到精通(視頻教學版)
- Java RESTful Web Service實戰
- 產品架構評估原理與方法
- Django 2.0 入門與實踐