如何在TouchableOpacity中垂直居中文本



我试图在TouchableOpacity中垂直居中文本,但很难为我完成。

我的应用程序.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设置为"中心",但我也尝试过:

  • text对齐:按钮标题中的"居中">
  • alignItems:按钮中的"center">
  • alignItems:"center",justifyContent:按钮中的"center">

还有我在谷歌上找到的许多其他方法,但都不起作用。它只将文本水平居中。有人能帮我垂直居中这个TouchableOpacity组件的文本吗?

提前感谢!

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

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

React原生文本复合

问题已解决:

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",
},
});

希望它能帮助那些遇到同样问题的人!

最新更新