css - React native, flex 和 width 父元素

标签 css reactjs react-native

使用 react native 和 flex,我这样写:

<View style={[styles.cell_content]}>
    <Text style={[styles.title]}>
        Sexualité et prévention
    </Text>
    ...


const styles = StyleSheet.create({
    cell_content: {
        flex: 1,
    },
    title: {
        backgroundColor: 'yellow'
        borderWidth: 1,
        borderRadius: 2.5,
        marginBottom: 5,
        padding: 5,
    },
})

这是结果:

enter image description here

但我希望黄色背景适应文本,而不是 100%。 如果我为标题 ( <View style={styles.title_container}><Text style={[styles.title]}>...</Text></View> ) 创建容器,这是相同的结果 ...

最佳答案

But I want the yellow background to be adapted to the text, not 100%

你可以包装你的 Text带有 View 的元素, 然后放一个虚拟 Text Text 旁边的元素覆盖剩余的空白空间。

像这样:

<View style={styles.container}>
    <Text style={styles.yourText}>
      Sexualité et prévention
    </Text>
    <Text style={styles.textDummy}/>
</View>

CSS:

  container: {
   flexDirection:"row",
  },
  yourText: {
    backgroundColor:"yellow"
  },
  textDummy: {
    flexGrow:1
  }

结果如下:

enter image description here


作为第二种解决方案,您可以添加

 alignSelf: "baseline"

到您的title .像这样:

 title: {
        backgroundColor: 'yellow'
        borderWidth: 1,
        borderRadius: 2.5,
        marginBottom: 5,
        padding: 5,
        alignSelf:"baseline"
    }

关于css - React native, flex 和 width 父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58507394/

相关文章:

html - 如何在不使用绝对定位和负边距的情况下从左到下切换位置?

javascript - 有条件地禁用父级的子级按钮 - React

javascript - 如何在 Quill Editor-React 中更改图像大小?

android - React Native Navigation Drawer 重叠状态栏

java - React-Native 构建发布apk 执行aapt失败

react-native - 如何创建带断点的圆形 slider ?

css - 如何在 FireFox 中为 SVG 使用十六进制值

javascript - 我的 <div class = content "> 与 nav-justified 重叠

javascript - 两个 Action 不能同时进行

javascript - getDetails() 中设置状态发生无限循环