React Native按钮对齐与样式设置:如何将按钮居中显示并减小厚度
实现方案
1. 核心修改逻辑
- 居中实现:给按钮外层的
View添加全屏占比和居中布局属性,通过flex布局实现水平+垂直居中 - 按钮变薄实现:React Native原生
Button组件样式自定义限制较多,推荐使用TouchableOpacity自定义按钮,可直接调整高度、内边距等参数实现变薄效果,兼容性更好
2. 完整修改后代码
import { View, TouchableOpacity, Text, StyleSheet } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; const Stack = createStackNavigator(); const MyStack = () => { return( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Principal" component={TelaPrincipal} options={{title:'欢迎来到首页'}} ></Stack.Screen> <Stack.Screen name="Tela02" component={Tela02} options={{title:'欢迎来到第二页'}} ></Stack.Screen> <Stack.Screen name="Tela03" component={Tela03} options={{title:'欢迎来到第三页'}} ></Stack.Screen> </Stack.Navigator> </NavigationContainer> ); }; const TelaPrincipal = ({navigation}) => { return( <View style={styles.container}> {/* 调整height参数可修改按钮厚度,值越小按钮越薄 */} <TouchableOpacity style={styles.button} onPress={() => navigation.navigate('Tela02', {name:'Tela02'})} > <Text style={styles.buttonText}>跳转到第二页</Text> </TouchableOpacity> </View> ); }; const styles = StyleSheet.create({ container: { // 占满全屏空间 flex: 1, // 垂直方向居中 justifyContent: 'center', // 水平方向居中 alignItems: 'center' }, button: { height: 32, backgroundColor: 'red', paddingHorizontal: 16, borderRadius: 4, justifyContent: 'center', alignItems: 'center' }, buttonText: { color: 'white', fontSize: 14 } })
3. 可选方案:保留原生Button的实现
如果坚持使用原生Button组件,可通过外层包裹View限制高度实现变薄效果,参考代码如下:
const TelaPrincipal = ({navigation}) => { return( <View style={styles.container}> <View style={{height: 30, overflow: 'hidden'}}> <Button title = '跳转到第二页' onPress= {() => navigation.navigate('Tela02', {name:'Tela02'})} color='red' /> </View> </View> ); };
内容的提问来源于stack exchange,提问作者Lucas Alves
相关产品推荐
相关产品推荐

