TouchableOpacity takes all available space even when width is set

时间:2017-10-10 18:39:37

标签: javascript react-native flexbox

I have followed this post-React Native flex-box align icon and text to make a button with a title as below:

<View style={styles.sectionHeaderContainer}>

  <Text style={styles.heading}>Work</Text>

  <TouchableOpacity
  style = {{width: 40, flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}
  onPress={() => {
    this.setState(previousState => {
      Alert.alert('You tapped the button!')
    });
  }}>
    <Image source={addIcon}/>
    <Text style={styles.tertirayTitleDark}>Add Work</Text> 
  </TouchableOpacity>

</View>

the stylesheet is as below:

  sectionHeaderContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-end',
    paddingHorizontal: "6%", 
    paddingTop: "12%",
  },
  heading: {
    fontSize: TITLE,
    fontWeight: 'bold',
    color: THEME_COLOR,
    backgroundColor:'transparent',
  },
  tertirayTitleDark: {
    fontSize: CONTENT_LARGE,
    fontWeight: 'bold',
    color: COLOR_DARK_PRIMARY,
  },

However the button is taking all available horizontal space left by the title:

enter image description here

I have tried many different settings but still can't figure out what I'm doing wrong here.

1 个答案:

答案 0 :(得分:4)

只需删除flex:1即可。当您将flex:1添加到touchableOpacity的样式时,您正好告诉它采取所有可用空间并像提供的图像一样运行。希望这有帮助!