React Native Note:Design

刻畫面必備知識,沒弄懂的話連勞動的權力都沒有。

Style

  • 只是組件的其中一個 props

Height and Width

Fixed Dimensions

將 width 跟 height 用數值表示固定尺寸
單位都是 density-independent pixels

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const FixedDimensionsBasics = () => {
return (
<View>
<View
style={{
width: 50,
height: 50,
backgroundColor: 'powderblue',
}}
/>
<View
style={{
width: 100,
height: 100,
backgroundColor: 'skyblue',
}}
/>
<View
style={{
width: 150,
height: 150,
backgroundColor: 'steelblue',
}}
/>
</View>
);
};

export default FixedDimensionsBasics;

Flex Dimensions

flex: 1 表示填充所有可用空間
如果父容器沒有指定的 width 跟 height 或是 flex,那麼父容器的大小就會是 0,將導致子視圖無法顯示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const FlexDimensionsBasics = () => {
return (
// Try removing the `flex: 1` on the parent View.
// The parent will not have dimensions, so the children can't expand.
// What if you add `height: 300` instead of `flex: 1`?
<View style={{flex: 1}}>
<View style={{flex: 1, backgroundColor: 'powderblue'}} />
<View style={{flex: 2, backgroundColor: 'skyblue'}} />
<View style={{flex: 3, backgroundColor: 'steelblue'}} />
</View>
);
};

export default FlexDimensionsBasics;

Percentage Dimensions

能直接指定百分比

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const PercentageDimensionsBasics = () => {
// Try removing the `height: '100%'` on the parent View.
// The parent will not have dimensions, so the children can't expand.
return (
<View style={{height: '100%'}}>
<View
style={{
height: '15%',
backgroundColor: 'powderblue',
}}
/>
<View
style={{
width: '66%',
height: '35%',
backgroundColor: 'skyblue',
}}
/>
<View
style={{
width: '33%',
height: '50%',
backgroundColor: 'steelblue',
}}
/>
</View>
);
};

export default PercentageDimensionsBasics;

更常用的方式是獲取設備窗口尺寸,再乘上 0~1 的小數達到比例效果

1
2
const windowWidth = Dimensions.get('window').width
const windowHeight = Dimensions.get('window').height

Layout with Flexbox

Flex Direction

flexDirection: column | row | column-reverse | row-reverse
指定 children 排序方向為垂直或水平

Layout Direction

direction: ltr | rtl
指定 layout 從左還右開始排

Justify Content

justifyContent: flex-start | flex-end | center | space-between | space-around | space-evenly
沿主軸方向處理 children

Align Items

alignItems: stretch | flex-start | flex-end | center | baseline
沿非主軸方向處理 children

Align Self

alignSelf: stretch | flex-start | flex-end | center | baseline
跟 alignItems 類似,不過是處理自己