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

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.
主站蜘蛛池模板: 汝阳县| 休宁县| 松原市| 中江县| 江川县| 耒阳市| 揭西县| 湖北省| 吉水县| 阿巴嘎旗| 黔西| 古蔺县| 郓城县| 铜山县| 交口县| 尉犁县| 上蔡县| 乌审旗| 盐城市| 织金县| 乌拉特后旗| 原平市| 普宁市| 通道| 武宁县| 蒙自县| 左云县| 黔江区| 布拖县| 班玛县| 湘西| 拜城县| 句容市| 黎平县| 铜川市| 沿河| 高碑店市| 锡林浩特市| 金华市| 金乡县| 仁化县|