How to make parent's width wrap its content in

2020-07-09 06:49发布

问题:

I am new to React Native so this might be a silly question.

What I am trying to get is something like this :

Where I have a parent view with 2 children, Image and Text, aligned vertically to the left. What I want is the parent view to cover only the width of its children. But instead what I get is this :

The parent view stretches to the complete width of the mobile screen.

Here is my code :

render () (<View style={{backgroundColor: '#333333'}}>
  <Image source={btnImageSource} />
  <Text>Some label</Text>
</View>);

Something similar to Android's 'wrap-content' width value.

回答1:

You will be able to do this using flex. I found this guide to be very helpful when working with flex.

A good starting point would be to create a parent View that is flexDirection: row, justifyContent: flex-start

render () (
    <View style={{justifyContent: 'flex-start', flexDirection: 'row'}}>
        <View style={{backgroundColor: '#333333'}}>
            <Image source={btnImageSource} />
            <Text>Some label</Text>
        </View>
    </View>
);