【发布时间】: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