- 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.
- LaTeX Cookbook
- SoapUI Cookbook
- Python爬蟲開發:從入門到實戰(微課版)
- MongoDB for Java Developers
- 算法訓練營:入門篇(全彩版)
- 零基礎入門學習Python(第2版)
- Building Android UIs with Custom Views
- Web性能實戰
- Elasticsearch Essentials
- Mastering Elixir
- Arduino機器人系統設計及開發
- jQuery從入門到精通(微課精編版)
- Python GUI Programming Cookbook(Second Edition)
- Java核心編程
- 可視化H5頁面設計與制作:Mugeda標準教程