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

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
}
});
主站蜘蛛池模板: 冷水江市| 皋兰县| 曲松县| 舒城县| 增城市| 孝义市| 玛曲县| 凯里市| 兰考县| 泾源县| 拉孜县| 武汉市| 全南县| 黑河市| 忻城县| 应城市| 改则县| 南投县| 崇州市| 廊坊市| 塔河县| 黎川县| 巩义市| 库伦旗| 靖州| 柞水县| 高唐县| 扎兰屯市| 龙江县| 筠连县| 呼和浩特市| 桐乡市| 沈阳市| 乌鲁木齐县| 乐东| 福安市| 岳西县| 武乡县| 临颍县| 洛川县| 博野县|