【问题标题】:How to translateX by percentage in React-Native?如何在 React-Native 中按百分比翻译 X?
【发布时间】:2021-07-21 08:24:12
【问题描述】:

我试图在 React-Native 中将一个绝对定位的组件水平居中,但我不知道它的宽度。

在 css 中我可以这样做:

position: absolute;
left: 50%,
transform: translateX(-50%);

但是当我在 React-Native 中进行等效操作时,它只会向左转换 50 而不是 50%。另外因为我试图在 Tab.Navigator 中将导航栏居中,所以我认为我不能将它包装在父组件中:

<Tab.Navigator
  barStyle={{
    position: "absolute",
    width: "95%",
    left: "50%",
    transform: [{ translateX: "-200" }],
    bottom: 5,
    overflow: "hidden",
    borderRadius: "50%",
  }}
>

EDIT 我要居中的组件是 导航栏。

【问题讨论】:

  • position: "absolute", width: "100%", textAlign: "center", 或者使用 alignItems: "center"
  • 谢谢,但我不想将宽度设置为 100%
  • 哦,也许使用 marginHorizo​​ntal : "auto",但我没有看到你的组件在视图中?理想的情况是发布您的一些组件
  • 不幸的是,marginHorizo​​ntal 不起作用,我添加了一个编辑 ^ 我要居中的组件是导航选项卡,它不在任何其他视图中,但我想将宽度设置为 95% 和水平居中
  • 嗯看Here

标签: react-native


【解决方案1】:

由于您知道Tab.Navigator 的宽度为 90%,因此您可以将 left 值设置为 5% 以使其在屏幕中居中,而无需使用 translate。

<NavigationContainer>
  <Tab.Navigator
    initialRouteName="Home"
    activeColor={'purple'}
    inactiveColor={'gray'}
    barStyle={{
      left: '5%', // <- this will center the navbar
      position: 'absolute',
      width: '90%',
      bottom: 20,
      overflow: 'hidden',
      borderRadius: '20%',
      backgroundColor: 'white',
    }}>
    <Tab.Screen name="Home" component={HomeScreen} />
    <Tab.Screen name="Camera" component={CameraScreen} />
    <Tab.Screen name="Profile" component={ProfileScreen} />
  </Tab.Navigator>
</NavigationContainer>

如果您需要更好的控制,则必须测量设备宽度、项目宽度并调整 left 值以确保其居中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-22
    • 2018-11-02
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 2021-04-15
    相关资源
    最近更新 更多