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

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
}
});
主站蜘蛛池模板: 蓬安县| 湖南省| 清河县| 昌图县| 伽师县| 沁阳市| 商丘市| 习水县| 封丘县| 拉萨市| 宁晋县| 景德镇市| 嘉峪关市| 万荣县| 鄂托克前旗| 汕头市| 锡林郭勒盟| 漳州市| 赤峰市| 高淳县| 丰都县| 凤城市| 长治县| 丰都县| 庆阳市| 南宁市| 陇西县| 西充县| 玉田县| 莱芜市| 赣榆县| 乐清市| 奇台县| 五大连池市| 潢川县| 叙永县| 贵州省| 铅山县| 隆尧县| 金溪县| 佛坪县|