在React Native iOS中,在图像上方呈现具有透明背景的文本框

35

我正在测试React Native时,尝试在图像上方呈现一个带有白色文本的块。但是,我得到的却是一个黑色块,并带有其中的白色文本。这不是我期望的结果。如何呈现具有透明背景的文本块?

当前结果

enter image description here

渲染函数

render: function(){
  return (
    <View style={styles.container}>
      <Image 
        style={styles.backdrop} 
        source={{uri: 'https://unsplash.com/photos/JWiMShWiF14/download'}}>
          <Text style={styles.headline}>Headline</Text>
      </Image>
    </View>
  );
)

样式表函数

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    backgroundColor: '#000000',
    width: 320
  },
  backdrop: {
    paddingTop: 60,
    width: 320,
    height: 120
  },
  headline: {
    fontSize: 20,
    textAlign: 'center',
    backgroundColor: 'rgba(0,0,0,0)',
    color: 'white'
  }
});

2
小心,这个已经被弃用了: "在子元素中使用<Image>已经被弃用,并且在不久的将来会出现错误。请重新考虑布局或改用<ImageBackground>。" - Victor Baron
4个回答

53
请注意:此答案现已过时。这适用于2015年React Native开源当天。今天这种方法已经被弃用。

“在不久的将来,使用 Image 的 children 将会被废弃并报错。请重新考虑布局或使用 View 代替。”

请参阅文档 https://reactnative.dev/docs/images#background-image-via-nesting




您可以通过在 Image 中添加一个View 来实现:

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>
  );
)

样式表函数

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'
  }
});

错别字,将“欢迎”替换为已定义的标题。 - Stefan Wallin
工作得很好。非常感谢。 - Nguyễn Anh Tuấn
是的 @blacksun,但你可以使用 ImageBackground,我已经使用过了,效果很好。 - MrBrownser
尝试这样做会导致错误:<Image> 组件不能包含子元素。 - Luiz Dias

8

backgroundColor: 'transparent' 实际上是一种性能优化方式,而且它非常具有攻击性。

"<Text>元素继承其父级<View>的背景颜色,但我认为这种行为会带来更多的麻烦而不是帮助。一个简单的例子是一个嵌套了<Text><Image>。文本节点将采用父视图的背景颜色或隐藏图像。然后,我们必须在文本节点上设置backgroundColor: 'transparent'来修复它。

这种行为在Android上也不会出现,默认情况下<Text>节点总是具有透明背景。这会导致在Android上开发某些东西时,然后在iOS上进行测试时产生一些惊喜。" - https://github.com/janicduplessis

这是用户提出问题的讨论内容。在此处阅读更多信息-https://github.com/facebook/react-native/issues/7964

如Colin所述,最简单的方法是将容器的backgroundColor设置为rgba(0,0,0,0)


7

从内部来看,我发现React Native确实将alpha值和特殊情况下的transparent转换为正确的带有alpha值的UIColor,因此这方面是有效的,而且很容易通过实验验证。

请注意,如果您将容器的backgroundColor设置为transparent(或rgba(0,0,0,0)),您还将获得透明的文本块-这个知识应该有助于解决这个问题。但是,我认为可能可以将其解释为错误,因为这不是人们期望的行为,感觉像某种堆叠问题。


2
我遇到了同样的问题。尝试从容器样式中删除backgroundColor: '#000000',。不确定为什么,但在这种情况下似乎会使用顶级组件的背景颜色。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接