I\'m trying to render a block with white text on top of an image in my testing of React Native. But instead i get a black block on top of my image with white text in it. Not wha
I just ran into the same problem. Try removing backgroundColor: '#000000',
from your container styles. Not sure why, but the background colour of the top-level component seems to be used in this case.
PLEASE NOTE: This answer is now vastly out of date. This was applicable the day React Native was open sourced back in 2015. Today this way of doing this is deprecated.
You can accomplish this by adding a View
inside the Image
like so:
render: function(){
return (
<View style={styles.container}>
<Image
style={styles.backdrop}
source={{uri: 'https://unsplash.com/photos/JWiMShWiF14/download'}}>
<View style={styles.backdropView}>
<Text style={styles.headline}>Headline</Text>
</View>
</Image>
</View>
);
)
Stylesheet function
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: '#000000',
width: 320
},
backdrop: {
paddingTop: 60,
width: 320,
height: 120
},
backdropView: {
height: 120,
width: 320,
backgroundColor: 'rgba(0,0,0,0)',
},
headline: {
fontSize: 20,
textAlign: 'center',
backgroundColor: 'rgba(0,0,0,0)',
color: 'white'
}
});
Internally, I see that React Native does translate alpha values and the special case of transparent
into the correct UIColor with alpha values, so that aspect of this is working and it's easy to validate this experimentally.
Notice that if you set the backgroundColor
of your container to transparent
(or rgba(0,0,0,0)
), you also get a transparent text block - that knowledge should help you work around this problem. However I think it's possible to interpret this as a bug since that's not the behaviour one would expect, it feels like some kind of stacking problem.
backgroundColor: 'transparent' This actually is a performance optimization and it is rather aggressive.
"< Text > elements inherit the background color of their parent < View > but this behavior causes more annoyance that helps in my opinion. A simple example is an < Image > with nested < Text >. The text nodes will take the background color or the parent views instead and will hide the image. Then we have to set backgroundColor: 'transparent' on the text nodes to fix it.
This behavior also doesn't happen on Android, the < Text > nodes always have a transparent background by default. This causes a few surprises when developing something on Android then testing it on iOS." - https://github.com/janicduplessis
This is from a discussion where users raised it as an issue. Read it more here - https://github.com/facebook/react-native/issues/7964
The easiest way like Colin said above is to set the backgroundColor of the container to rgba(0,0,0,0)