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

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.

Please note that the  fontFamily  key in style object accepts String values and may differ between platforms (some are accepted on Android and some are accepted on iOS). For consistency, you may need to use a custom font. The setup is rather easy but takes a while and so exceeds the design patterns topic of this book. To learn more, visit https://docs.expo.io/versions/latest/guides/using-custom-fonts.

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
}
});
主站蜘蛛池模板: 峡江县| 新巴尔虎左旗| 宁海县| 涡阳县| 图们市| 本溪市| 湘潭市| 曲麻莱县| 濮阳县| 临桂县| 桓仁| 丹阳市| 大埔县| 富民县| 新平| 山西省| 昌图县| 丹江口市| 洛南县| 巴塘县| 和田县| 武定县| 丘北县| 禹城市| 奉化市| 同心县| 韶关市| 泊头市| 正安县| 滕州市| 彰武县| 玉田县| 会宁县| 辽阳市| 峨眉山市| 湘潭市| 沙雅县| 通许县| 鲜城| 宜川县| 丹东市|