- Hands-On Design Patterns with React Native
- Mateusz Grzesiukiewicz
- 334字
- 2021-08-13 15:13:04
Workaround for limited inheritance
Imagine a situation where you would like to reuse the same font across the whole application. Given the mentioned inheritance limitations, how would you do that?
The solution is a mechanism that we have learned already: component composition. Let's create a component that satisfies our requirements:
// src/ Chapter_3/ Example_3/ src/ AppText.js
const AppText = ({ children, ...props }) => (
<Text style={styles.appText} {...props}>
{children}
</Text>
);
// ... propTypes and defaultProps omitted for clarity
const styles = StyleSheet.create({
appText: {
fontFamily: 'Verdana'
}
});
export default AppText;
The AppText component just wraps the Text component and specifies its styles. In this simple example, it's just fontFamily.
Think about how to edit AppText to support custom styles so that it will be possible to override specified keys.
Is the style object override the best solution in this case? Perhaps not; you have created this component to unify styles, not to allow overrides. But, you may say that it could be needed to create another component, such as HeaderText or something similar. You need a way to reuse existing styles and still enlarge the text. Luckily, you can still use Text inheritance here:
// src / Chapter 3 / Example 3 / App.js
export default () => (
<View style={styles.container}>
<AppText>
some text, Verdana font
<Text style={styles.big}>
some big text, Verdana font
</Text>
</AppText>
<Text style={styles.big}>
some normal big text
</Text>
</View>
);
Hence, HeaderText would be very simple to implement. Check the following code:
// src / Chapter 3 / Example 3 / src / HeaderText.js
const HeaderText = ({ children, ...props }) => (
<AppText>
<Text style={styles.headerText} {...props}>
{children}
</Text>
</AppText>
);
// ...
const styles = StyleSheet.create({
headerText: {
fontSize: 30
}
});
- Java程序設計(慕課版)
- WildFly:New Features
- Visual Basic學習手冊
- 大學計算機基礎(第2版)(微課版)
- PHP+MySQL網站開發項目式教程
- Getting Started with Python Data Analysis
- Java:High-Performance Apps with Java 9
- Python:Deeper Insights into Machine Learning
- Instant jQuery Boilerplate for Plugins
- Mastering Object:Oriented Python(Second Edition)
- 一覽眾山小:ASP.NET Web開發修行實錄
- Spring Boot從入門到實戰
- 虛擬現實:引領未來的人機交互革命
- Linux Networking Cookbook
- Getting Started with Hazelcast