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

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.

If you are interested in how styles work, we will deep dive into patterns involving them in   Chapter 3, Styling Patterns. You will also learn about the flexbox pattern from CSS and many other conventions.

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.

If you come from a backend background, you may quickly jump into assumptions that it is just like the  MVC pattern: Model, View, and Controller. It is not necessarily 1:1 relation, but in general, you may simplify it to the following:
  • 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.
主站蜘蛛池模板: 砀山县| 舟曲县| 金门县| 开远市| 武定县| 安徽省| 津南区| 兰西县| 屏东市| 东海县| 忻城县| 高阳县| 亚东县| 安平县| 靖安县| 比如县| 河津市| 胶州市| 武威市| 桦南县| 丹棱县| 广宗县| 徐水县| 垣曲县| 农安县| 都昌县| 沾化县| 上蔡县| 金川县| 亚东县| 越西县| 江门市| 鹤山市| 萝北县| 五大连池市| 宜宾县| 丰城市| 崇左市| 海兴县| 榆中县| 随州市|