【问题标题】:Displaying line bellow TouchableOpacity options wrapped in a View at the border of parent在父边框的视图中显示包裹在 View 中的 TouchableOpacity 选项
【发布时间】:2019-10-01 16:19:23
【问题描述】:

我在 React Native 中有一个类似菜单的组件,它被包装在一个视图中。此视图有 3 个选项。我希望每个选项在其下方都有一条几乎触及视图边框的线。

为了实现这一点,我有三个带有文本和视图的 TouchableOpacities,它们都包装在同一个父级下。这是我的代码的样子:

export function Menu () {
  return (
    <View style={{
      flex: 1,
      flexDirection: 'row',
      backgroundColor: 'grey',
      height: 50,
      justifyContent: 'space-around',
      alignContent: 'center',
      alignItems: 'center'
    }}>
      <TouchableOpacity>
        <Text>Option 1</Text>
        <View
          style={{
            width: 50,
            height: 4,
            backgroundColor: 'red',
            paddingTop: 0,
            marginTop: 25,
            marginBottom: 0
          }}
        />
      </TouchableOpacity>
      <TouchableOpacity> <Text>Option 2</Text> </TouchableOpacity>
      <TouchableOpacity> <Text>Option 3</Text> </TouchableOpacity>
    </View>
  )
}

这里的问题是,通过marginTop: 25 将内部视图放在底部,我将文本推送到其父级的顶部,这是我不想要的。这是这段代码的结果:

查看选项 2 和选项 3 如何在其父项中居中?这正是我希望选项 1 的样子,但在灰色框边缘的红线包裹了所有三个选项。

如何做到这一点?

【问题讨论】:

  • &lt;Text /&gt; 上方红线&lt;View&gt; 的样式设置为flex:1 并从&lt;View&gt; 中删除marginTop: 25

标签: javascript css react-native react-native-stylesheet


【解决方案1】:

&lt;Text&gt; 包裹在&lt;View&gt; 中。自从我上次从事 RN 工作以来已经有一段时间了,但我认为这段代码应该会给你想要的结果。

<TouchableOpacity>
  <View style={{flex: 1, alignItems: 'center', height: 46}}><Text>Option 1</Text></View>
  <View
      style={{
        width: 50,
        height: 4,
        backgroundColor: 'red',
        paddingTop: 0,
        marginTop: 25,
        marginBottom: 0
      }}
    />
</TouchableOpacity>

PS:我认为即使没有 height: 46&lt;View&gt; 也应该可以工作,但我目前无法对其进行测试,因此无法保证。

【讨论】:

  • 完美!不需要将文本包装在视图中,否则就可以了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多