- Hands-On Design Patterns with React Native
- Mateusz Grzesiukiewicz
- 323字
- 2021-08-13 15:12:56
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.
- Python Deep Learning
- Learning SAP Analytics Cloud
- Mastering Unity Shaders and Effects
- C語言從入門到精通(第4版)
- Apache Kafka Quick Start Guide
- Python之光:Python編程入門與實(shí)戰(zhàn)
- Learning Node.js for .NET Developers
- Programming Microsoft Dynamics? NAV 2015
- 單片機(jī)原理及應(yīng)用技術(shù)
- 基于GPU加速的計(jì)算機(jī)視覺編程:使用OpenCV和CUDA實(shí)時(shí)處理復(fù)雜圖像數(shù)據(jù)
- 數(shù)據(jù)結(jié)構(gòu):Python語言描述
- Kotlin語言實(shí)例精解
- Python趣味創(chuàng)意編程
- 情境微課開發(fā)(第2版)
- 開發(fā)者測(cè)試