【问题标题】:How to vertically center Text in TouchableOpacity?如何在 TouchableOpacity 中垂直居中文本?
【发布时间】:2021-09-14 09:56:01
【问题描述】:

我正在尝试在 TouchableOpacity 中垂直居中文本,但我很难做到。

我的 App.tsx:

import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, View } from "react-native";

import { CustomButton } from "./src/components/CustomButton";

export default function App() {
  return (
    <View style={styles.container}>
      <CustomButton title="Button" />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
  },
});

还有我的 CustomButton.tsx:

import React from "react";
import {
  TouchableOpacity,
  StyleSheet,
  Text,
} from "react-native";

interface CustomButtonProps {
  title: string;
}

export const CustomButton = ({ title }: CustomButtonProps): JSX.Element => {
  return (
      <TouchableOpacity style={styles.button}>
        <Text style={styles.buttonTitle}>{title}</Text>
      </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    borderRadius: 4,
    width: 240,
    height: 100,
    backgroundColor: "#FFF",
    marginBottom: 12,
  },
  buttonTitle: {
    alignSelf: "center",
    fontSize: 24,
    color: "#fff",
    fontWeight: "bold",
  },
});

目前我在 buttonTitle 中将alignSelf 设置为“中心”,但我也尝试过:

  • textAlign:按钮标题中的“居中”,
  • alignItems:按钮中的“中心”,
  • alignItems: 'center', justifyContent: 'center' in button

还有很多其他方法我可以在 Google 上找到,但都没有奏效。它仅将文本水平居中。谁能帮助我垂直将此 TouchableOpacity 组件的文本居中?

提前致谢!

【问题讨论】:

  • 必须是 display: flex 才能处理您的 justify-content 属性。您正在寻找display: "flex",alignItems: "center"display: "flex", flexFlow: "column". justifyContent: "center"。这个问题是关于 CSS,而不是 React,甚至不是关于 Text in TouchableOpacity。详细了解flex at MDN
  • 您的建议都不起作用,而且 flexFlow 在 React Native 中甚至无效。你看到 CSS 在标签中了吗?你是什​​么意思这个问题甚至与 Text 或 TouchableOpacity 无关,因为它们实际上是我想要使用的? :)
  • 而我所做的实际上是按照 React Native 文档中的示例进行操作:reactnative.dev/docs/touchableopacity 似乎以我尝试使用但不适用于我的属性的相同属性为中心。跨度>
  • 在按钮样式中设置 justifyContet: 'center', alignItems: 'center'。 :)

标签: javascript css reactjs typescript react-native


【解决方案1】:

尝试在文本组件的样式中使用textAlign: 'center'

另外,您可以从这里参考官方文档。

React native Text Compoent

【讨论】:

  • 我已经尝试过(写在帖子中)但它不起作用..我可能错过了什么?
【解决方案2】:

问题解决了:

React Native 的默认方向是 column,这与 web 不同。

因此,我需要在button 样式中添加justifyContent: "center",因此代码如下所示:

const styles = StyleSheet.create({
  button: {
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 4,
    width: 240,
    height: 100,
    backgroundColor: "#FFF",
    marginBottom: 12,
  },
  buttonTitle: {
    fontSize: 24,
    color: "#fff",
    fontWeight: "bold",
  },
});

希望对遇到同样问题的人有所帮助!

【讨论】:

    猜你喜欢
    • 2013-10-15
    • 1970-01-01
    • 2012-11-13
    • 2017-04-05
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2015-09-16
    相关资源
    最近更新 更多