- 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.
推薦閱讀
- Java語言程序設計
- HTML5+CSS3+JavaScript從入門到精通:上冊(微課精編版·第2版)
- Advanced Machine Learning with Python
- Python自然語言處理實戰:核心技術與算法
- Effective C#:改善C#代碼的50個有效方法(原書第3版)
- C/C++算法從菜鳥到達人
- C語言程序設計(第2版)
- Building Mapping Applications with QGIS
- Getting Started with SQL Server 2012 Cube Development
- Big Data Analytics
- Cocos2d-x學習筆記:完全掌握Lua API與游戲項目開發 (未來書庫)
- Processing創意編程指南
- BeagleBone Robotic Projects(Second Edition)
- 多媒體技術及應用
- Visual FoxPro程序設計實驗教程