不确定为啥按钮不在本机反应的中心

Posted

技术标签:

【中文标题】不确定为啥按钮不在本机反应的中心【英文标题】:Unsure why button is not in the center in react native不确定为什么按钮不在本机反应的中心 【发布时间】:2021-10-09 21:39:47 【问题描述】:

我最近开始使用 react native 进行编程,我正在尝试实现一个位于屏幕底部中心的按钮,一旦按下该按钮就会捕获图像。现在,当我在手机上运行应用程序时,我创建的红色按钮出现在左下角,即使我在样式表中使用 alignItems: 'center' 将其居中。我尝试在样式表中使用right: '50%' 来查看它是否会出现在屏幕中间,但没有。我不知道现在该怎么做,这是我的代码:

import  Camera  from 'expo-camera';
import React,  useState, useEffect  from 'react';
import  StyleSheet, Text, View, TouchableOpacity, Button, Alert, TouchableNativeFeedback, Image, SafeAreaView  from 'react-native';




export default function App() 
  const buttonClickedHandler = () => 
    console.log('Picture Taken');
  ;


  // Camera Permissions
  const [hasPermission, setHasPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);

  useEffect(() => 
    (async () => 
      const  status  = await Camera.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    )();
  , []);

  if (hasPermission === null) 
    return <View />;
  
  if (hasPermission === false) 
    return <Text>No access to camera</Text>;
  

  return (
    <View style=styles.container>
      <Camera style=styles.camera type=type />
      
      //BUTTON
      <TouchableOpacity
          onPress=buttonClickedHandler
          style=styles.pictureButton>
      </TouchableOpacity>
    </View>
  );


const styles = StyleSheet.create(
  pictureButton: 
    width: 90,
    height: 90,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
    borderRadius: 100,
    backgroundColor: 'red',
    position: 'absolute',
    bottom: 20,
  ,
  container: 
    flex: 1,
  ,
  camera: 
    flex: 1,
  ,
  text: 
    fontSize: 18,
    color: 'white',
  ,
);

【问题讨论】:

【参考方案1】:

绝对定位元素会从文档流中移除,因此alignItems: 'center' 等属性将被忽略。

尝试使用类似的东西:

 pictureButton: 
    width: 90,
    height: 90,
    padding: 10,
    borderRadius: 100,
    backgroundColor: 'red',
    position: 'absolute',
    bottom: 20,
    left: 50%,
    transform: translateX(-50%),
  

Here 深入解释了绝对定位的工作原理

【讨论】:

感谢您的回复。当我输入您提供的代码时,我收到一个错误,主要是因为“transform: translateX(-50%),”。我收到意外的令牌错误。当我删除变换部分时,它工作正常,但它仍然没有完全居中在中间。有什么我有进口的吗?我尝试导入“translateX”,但我的 expo 应用程序在运行后不断崩溃。关于为什么转换不起作用的任何想法? 尝试在翻译属性transform: "translateX(-50%)"周围添加引号 它仍然出现错误,错误是:“不变量违规:提供给样式表图片按钮的类型字符串的道具转换无效,需要一个数组。”出于某种原因,transformtranslate 无法正常工作,我可以用什么来替换它还是我应该做些什么? 您可以尝试将display: 'flex'添加到容器中,并将alignSelf: 'center',添加到按钮中。这个线程也有一些选项:***.com/questions/37317568/…

以上是关于不确定为啥按钮不在本机反应的中心的主要内容,如果未能解决你的问题,请参考以下文章

键盘类型 - 反应本机

为啥我的 TextInput 字段在不同的屏幕上表现不同。在本机反应

为啥这个 CSS 按钮不在 div 中居中?

反应本机 ListView 数据源不更新

为啥不使用实时打包服务器进行生产?反应本机[关闭]

SweetAlert2 第一次提示为啥不在中间