React Native-flexDirection问题

时间:2019-11-02 19:17:08

标签: react-native react-native-android

我试图在视图中放置一个按钮(由Viewable中的TouchableOpacity制成的自定义组件)和一个图像.....并将它们并排放置。
参见下面的代码

<View
  style={{
    borderColor: 'black',
    borderWidth: 1,
    flex: 1,
    flexDirection: 'row',
  }}
>
  <MyButton
    to_extraStyle={{
      backgroundColor: '#03A9F4',
      width: 100,
      height: 60,
      alignSelf: 'flex-start',
    }}
    onPress={this._imagePickHandler}
  >
    CHOOSE PIC
  </MyButton>
  <Image
    source={{ uri: this.state.localImgUrl }}
    style={{
      width: 100,
      height: 60,
      borderColor: 'black',
      borderWidth: 1,
      alignSelf: 'flex-end',
    }}
  />
</View>

当我移除flexDirection: 'row'时,您可以同时看到图像和按钮。...它们彼此叠放....但是包括了flexDirection: 'row',图像消失了,您可以只看到按钮。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

将width的值用作%

<View
  style={{
    borderColor: 'black',
    borderWidth: 1,
    flex: 1,
    flexDirection: 'row'
  }}
>
  <MyButton
    to_extraStyle={{
      backgroundColor: '#03A9F4',
      width: "50%",
      height: 60,
    }}
    onPress={this._imagePickHandler}
  >
    CHOOSE PIC
  </MyButton>
  <Image
    source={{ uri: this.state.localImgUrl }}
    style={{
      width: "50%",
      height: 60,
      borderColor: 'black',
      borderWidth: 1,
    }}
  />
</View>

示例

export default class App extends Component {
  render() {
    return (
      <View style={s.container}
>
 <TouchableOpacity style={s.touchable}>
      <Text style={{color:"#ffffff"}}>Button </Text>
 </TouchableOpacity>
      <Image source={{uri: 'http://i.imgur.com/IGlBYaC.jpg'}} style={s.backgroundImage} />
      </View>
    );
  }
}

const s = StyleSheet.create({
  backgroundImage: {
      width: "50%",
      height: 60,
      borderColor: 'black',
      borderWidth: 1,
  },
  touchable: {      
   backgroundColor: '#03A9F4',
      width: "50%",
      height: 60,
      justifyContent:"center",
      alignItems:"center"
      },
  container: {
    borderColor: 'white',
    borderWidth: 1,
    flex: 1,
    flexDirection: 'row'
  }
});

enter image description here

答案 1 :(得分:0)

同时移除alignSelfMyButton上的Image,它们将并排放置。

如果要使用alignSelf获得的结果是将MyButton对齐到最左侧,将Image对齐到最右侧,则将justifyContent: 'space-between'添加到视图中。