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

Component composition

If you have learned any Object-Oriented (OO) language, you may have used inheritance extensively. In JavaScript, this concept is a little bit different. JavaScript inheritance is based on prototypes, and so we call it prototypal inheritance. Functionalities are not copied to the object itself—they are inherited from the prototype of the object and possibly even through other prototypes in the prototype tree. We call this a prototype chain.

However, in React, using inheritance is not very common. Thanks to components, we can embrace another pattern called component composition. Instead of creating a new class and inheriting from the base class, we will create a new parent component that will use its child component to make itself more specific or more powerful. Let's look at an example:

// src/ Chapter 1/ Example_6_Component_composition_red_text/ App.js

const
WarningText = ({style, ...otherProps}) => (
<Text style={[style, {color: 'orange'}]} {...otherProps} />
);

export default class App extends React.Component {
render = () => (
<View style={styles.container}>
<Text style={styles.text}>Normal text</Text>
<WarningText style={styles.text}>Warning</WarningText>
</View>
);
}

The App component is being built out of three components: View, Text, and WarningText. It is a perfect example of how one component, through composition, can reuse the capabilities of others. 

The WarningText component uses composition to enforce the orange text color in the Text component. It makes the generic Text component more specific. Now, we can reuse WarningText in any place of the app where it is necessary. If our app designer decides to alter the warning text, we can quickly adapt to the new design in one place.

Note the implicit pass of a special prop called children. It represents the children of the component. In Example 6_ Component composition - red text, we first pass warning text as children to the  WarningText component and then using the  spread operator it is  passed to the  Text component, which WarningText encapsulates.
主站蜘蛛池模板: 郓城县| 乌苏市| 外汇| 大冶市| 若尔盖县| 新宁县| 诏安县| 民县| 北流市| 柘荣县| 海盐县| 泊头市| 平塘县| 龙海市| 融水| 隆回县| 吐鲁番市| 信阳市| 呼和浩特市| 闽清县| 红原县| 穆棱市| 汶川县| 长子县| 诏安县| 冷水江市| 佛教| 仙居县| 兴国县| 札达县| 交口县| 浏阳市| 民丰县| 资阳市| 丰原市| 和顺县| 鄂伦春自治旗| 福贡县| 东丽区| 龙游县| 绩溪县|