2017-08-15 72 views
0

我需要每行添加3個按鈕。由於有許多設備大小,我擔心我的代碼每行會返回不同數量的按鈕。我該如何分類?對齊按鈕,以便只有3個按鈕連成一排

因此,它的設備寬度是多少,代碼應該每行只返回3個按鈕。該按鈕的寬度應根據寬度自動收縮以適應每行3個按鈕。

我的代碼目前每行返回3個按鈕,但是當屏幕寬度發生變化時,數字會發生變化。

... 
    mygetButtons =() => { 
    const buttons = []; 
    for(let i = 0; i < 9; i++) { 
     buttons.push(
     <TouchableOpacity style={styles.but} key={i}> 

      <Text> Hi </Text> 

     </TouchableOpacity> 
    ) 
    } 
    return buttons; 
    } 

... 

<View style={styles.frame}> 
     {this.mygetButtons()} 
</View> 

... 

    frame: { 
    flex: 0.5, 
    flexDirection: 'row', 
    flexWrap: 'wrap', 
    width: window.width 
    }, 
    but: { 
    flexDirection: 'row', 
    flexWrap: 'wrap', 
    paddingTop: 15, 
    paddingRight : 115, 
    paddingLeft: 5, 

    } 
+0

嗯,我不熟悉反應,但在'正常'Android中,您可以使用[Li nearLayout](https://developer.android.com/guide/topics/ui/layout/linear.html)和[layout_weight](https://stackoverflow.com/questions/3995825/what-does-androidlayout-weight-意思是) – Ch4t4r

+0

你可以使用視圖通過給它flexWrap ...看到[this](https://stackoverflow.com/questions/45328984/draw-a-view-with-image-pattern/45329732#45329732)回答它會幫幫我 –

回答

0

您可以使用Dimensions.width以實現此目的。

設置你的framebutton寬度如你所願

const {width} = Dimensions.get('window'); 

const frameWidth = width; 
const columnWidth = frameWidth/3; 

,並利用它們

frame: { 
    flexDirection: 'row', 
    flexWrap: 'wrap', 
    alignItems:'flex-start', 
    justifyContent:'flex-start', 
    width: frameWidth, 
    backgroundColor:'blue', 
}, 
but: { 
    width: columnWidth, 
    paddingTop: 15, 
    paddingBottom: 15, 
    alignItems:'center', 
    backgroundColor:'green' 
} 

working example

1

您可以通過使用Dimensions歸檔此爲@Qop提到here

另一種方法是使用一個包react-native-easy-grid,讓您無需擔心設備的尺寸創建基於需求的行和列,

進口:

import { Col, Row, Grid } from "react-native-easy-grid"; 

使用:

<Grid> 
    <Col></Col> 
    <Col></Col> 
</Grid> 

這將創建兩個等寬的列,即設備寬度的50%