官术网_书友最值得收藏!

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 this example, we used  componentDidMount, which is one of the component life cycle hooks. These can be used in ES6 classes, too. Please check out the official documentation for insights about the other methods:  https://reactjs.org/docs/react-component.html#the-component-lifecycle.

In case you need more loggers, you can mix them into a single component by using a comma:

...
mixins
: [LoggerMixin, LoggerMixin2],
...
This is a book on patterns, so it is crucial to stop here and look at the  createReactClass function.

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.
主站蜘蛛池模板: 郸城县| 买车| 大兴区| 通道| 莱芜市| 江川县| 南郑县| 景泰县| 淮南市| 香格里拉县| 大名县| 名山县| 临江市| 新绛县| 潍坊市| 保山市| 新晃| 富蕴县| 剑河县| 许昌县| 五华县| 蛟河市| 疏附县| 丰顺县| 湖南省| 屯昌县| 衡水市| 蒙山县| 安国市| 乌拉特中旗| 泗水县| 和田县| 石门县| 理塘县| 改则县| 波密县| 滕州市| 通城县| 玉龙| 嘉定区| 两当县|