- Hands-On Design Patterns with React Native
- Mateusz Grzesiukiewicz
- 388字
- 2021-08-13 15:13:02
Mixin example
Instead of shouting Mixins are harmful, let's create a component that is using them and look at what the issues are. Mixins are deprecated, so the first step is finding a way to use them. It turns out that they still live in a legacy way of creating React class components. Previously, instead of ES6 classes, there was a special function called createReactClass. In one of the major releases, the function was removed from the React library and is now available in a separate library called 'create-react-class':
// Chapter 2_View patterns/Example 12/App.js
...
import createReactClass from 'create-react-class';
const LoggerMixin = {
componentDidMount: function() { // uses lifecycle method to log
console.log('Component has been rendered successfully!');
}
};
export default createReactClass({
mixins: [LoggerMixin],
render: function() {
return (
<View>
<Text>Some text in a component with mixin.</Text>
</View>
);
}
});
Here, we create LoggerMixin, which is taking care of logging the necessary information. In this simple example, it's just information regarding that component that has been rendered, but it could be easily extended further.
In case you need more loggers, you can mix them into a single component by using a comma:
...
mixins: [LoggerMixin, LoggerMixin2],
...
Why has it been deprecated? The answer is actually pretty simple. The React Team prefers explicit APIs over implicit APIs. The CreateReactClass function is another implicit abstraction that hides implementation details from you. Instead of adding a new function, it is better to use the standard way: ES6 classes. ES6 classes have their own cons, but that is another topic entirely. Additionally, you may use classes in other languages that are built on top of ECMAScript, for instance, TypeScript. This is a huge advantage, especially nowadays, with TypeScript going mainstream.
To find out more on this thought process, I recommend that you watch a great talk from Sebastian Markb?ge called Minimal API Surface Area. It was originally delivered at JSConf EU in 2014, and can be found at https://www.youtube.com/watch?v=4anAwXYqLG8.
- 現代C++編程:從入門到實踐
- 網店設計看這本就夠了
- 深入淺出Serverless:技術原理與應用實踐
- Python Data Analysis Cookbook
- Python極簡講義:一本書入門數據分析與機器學習
- Python機器學習算法: 原理、實現與案例
- 從零開始:UI圖標設計與制作(第3版)
- 貫通Tomcat開發
- Tableau Desktop可視化高級應用
- Node.js實戰:分布式系統中的后端服務開發
- 算法超簡單:趣味游戲帶你輕松入門與實踐
- PhantomJS Cookbook
- 少年小魚的魔法之旅:神奇的Python
- MonoTouch應用開發實踐指南:使用C#和.NET開發iOS應用
- C++程序設計習題與實驗指導