问题
I'm trying to place two (or more) components above each others, centered vertically and horizontally in a view that wraps this content (i.e., the height of this outer view should be the max height of the components inside; idem for the width).
At first, absolute positioning looked like a good idea to have all the components centered above each other. However then I don't know how to get the outer view to wrap the content.
<View style={{ backgroundColor: 'black', alignItems: 'center', justifyContent: 'center'}}>
<View style={{position: 'absolute', width: 60, height: 60, backgroundColor: 'blue'}} />
<View style={{position: 'absolute', width: 70, height: 50, backgroundColor: 'red'}} />
<View style={{position: 'absolute', width: 50, height: 70, backgroundColor: 'green'}} />
</View>
With this examples, we cannot see any of the black background of the outer View (whose size is probable 0x0), whereas I'm expecting a 70x70 black square behind the three colored rectangles.
回答1:
The outermost View will not automatically adjust to its children if their position is absolute.
You would have to make the outermost View's position absolute and calculate its size and position based on its children and the screen's width and height.
Another option is to create a background View as a child with a position of relative like this:
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<View style={{position: 'relative', width: 70, height: 70, backgroundColor: 'black'}} />
<View style={{position: 'absolute', width: 60, height: 60, backgroundColor: 'blue'}} />
<View style={{position: 'absolute', width: 70, height: 50, backgroundColor: 'red'}} />
<View style={{position: 'absolute', width: 50, height: 70, backgroundColor: 'green'}} />
</View>
来源:https://stackoverflow.com/questions/54278874/stack-components-centered-above-each-other-in-react-native