如何在 React-Native 中按百分比翻译 X?

Ken*_*Ken 9 react-native

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

在CSS中我可以这样做:

position: absolute;
left: 50%,
transform: translateX(-50%);
Run Code Online (Sandbox Code Playgroud)

但是当我在 React-Native 中做同样的事情时,它只转换了 50%,而不是 50%。另外,因为我试图将导航栏置于 Tab.Navigator 的中心,所以我认为我无法将其包装在父组件中:

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

编辑我试图居中的组件是 <Tab.Navigator> 导航栏。

nip*_*777 4

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

<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>
Run Code Online (Sandbox Code Playgroud)

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