- 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
}
});