- Hands-On Design Patterns with React Native
- Mateusz Grzesiukiewicz
- 397字
- 2021-08-13 15:12:57
Decoupling styles
In the preceding examples, you may have noticed that styles are tightly coupled to presentational components. Why tightly? Because we explicitly include them by using style={styles.container}, but the styles object is not configurable. We cannot replace any style part with props, and that tightly couples us to the existing implementation. In some cases, this is a desired behavior, but in others, it is not.
You will bump into this problem if you have tried to split code into separate files. How can we fix this issue?
Let the styles be the optional prop. If styles are not provided, then we can fall back to the default values:
// src/ Chapter_1/ Example_10_Decoupling_styles/ App.js
export const HelloBox = ({
isExpanded,
expandOrCollapse,
containerStyles,
expandedTextStyles
}) => (
<View style={containerStyles || styles.container}>
<HelloText onPress={() => expandOrCollapse()}>...</HelloText>
<HelloText onPress={() => expandOrCollapse()}>...</HelloText>
{
isExpanded &&
<HelloText style={expandedTextStyles || styles.text}>
...
</HelloText>
}
</View>
);
Notice the use of the || operator. In the preceding example (expandedTextStyles || styles.text), it first checks if expandedTextStyles is defined and if so returns that value. If expandedTextStyles is undefined, then it return styles.text, which is a default style object that was hard-coded by us.
Now, if we wish, in some places, we can override our styles by passing respective props:
render = () => (
<HelloBox
isExpanded={this.state.expanded}
expandOrCollapse={this.expandOrCollapse}
expandedTextStyles={{ color: 'red' }}
/>
);
This is how we split markup, styles, and logic. Remember to use presentational components as often as possible to make your features truly reusable across many screens/views.
- View: This is a presentational component.
- Model: This is a data representation, which in our case is the state that is built either in a stateful component or using so-called store and reducers (check Chapter 5, Store Patterns, to learn more details about what Redux is and how to use it).
- Controller: This is a container component that is responsible for application logic, including event handlers and services. It should be lean and import logic from the respective files.
- Modular Programming with Python
- 控糖控脂健康餐
- Mastering Spring MVC 4
- C語言程序設計教程(第2版)
- 跟小海龜學Python
- Practical Windows Forensics
- Rust游戲開發實戰
- 零基礎學Scratch 3.0編程
- 超簡單:用Python讓Excel飛起來(實戰150例)
- 物聯網系統架構設計與邊緣計算(原書第2版)
- Shopify Application Development
- 原型設計:打造成功產品的實用方法及實踐
- Serverless從入門到進階:架構、原理與實踐
- Access 2010數據庫教程(微課版)
- Learning Puppet Security