【问题标题】:How to center form elements in React Native如何在 React Native 中居中表单元素
【发布时间】:2021-08-23 02:28:34
【问题描述】:

我正在 react-native 中创建登录表单我想将登录表单放在中心。虽然表单在中心,但按钮没有像 TextInput 一样采用全宽和边距。

截图如下:

下面是我的代码:

Login.js

import React from 'react';
import {View,Button,Text, TextInput, StyleSheet} from 'react-native';

const Login = ({navigation}) => {

 return(
    <View style={styles.loginBox}>
        
        <Text style={styles.login}>Login</Text>
        <TextInput style={styles.input} placeholder="Username"/>
        <TextInput style={styles.input} placeholder="Password"/>    
        <Button style={styles.butStyle} title="LOGIN"/>
    
    </View>
  )
}

const styles = StyleSheet.create({
 loginBox:{
     flex:1,
     alignItems:'center',
     justifyContent:'center'
 },
 login:{
   fontWeight:'bold',
   fontSize:20
 }, 
 input:{
     borderRadius:5,
     borderColor: "#adadad",
     borderWidth:2,
     marginTop:15,
     marginLeft:15,
     marginRight:15,
     paddingLeft:15,
     alignSelf: 'stretch'
 },
 butStyle:{
     borderRadius:5,
     marginTop:10,
     margin:15,
 }   
});

export default Login;

以上代码中需要修正什么?

【问题讨论】:

  • 这能回答你的问题吗? Full width button w/ flex-box in react-native
  • 我已经看过这篇文章,但是alignSelf: 'stretch' 属性不适用于按钮样式。
  • 你有没有尝试像 cmets 中提到的那样用flex:1 包裹另一个View?我知道你有它在一个视图中,但它也有 justifyContent 和 alignItems,我只是想知道它是否覆盖了 alignSelf。我个人不使用 React Native,所以我没有检查..

标签: javascript reactjs react-native


【解决方案1】:

如果您使用的是最新的 react-native>=0.63,则可以使用新的 Pressable 组件。

<Pressable onPress={onPressFunction}>
  <Text>Login</Text>
</Pressable>

【讨论】:

    【解决方案2】:

    在这种情况下,您可以使用 TouchableOpacity

        <TouchableOpacity style={{backgroundColor:"blue", alignSelf:"stretch", marginHorizontal:15, padding:15, marginTop:15 , justifyContent:"center", alignItems:"center", borderRadius: 5}}>
              <Text style={{color:"white" , fontWeight:"bold"}}>Login</Text>
        </TouchableOpacity>
    

    【讨论】:

    • 你能告诉我怎样才能使表格稳定,因为当键盘打开时它会向上移动。
    • 登录Login
    • 我需要从&lt;KeyboardAvoidingView&gt; &lt;/KeyboardAvoidingView&gt;中的元素换行吗
    • 我试过KeyboardAvoidingView它不起作用。
    • 我刚刚在清单文件中添加了这一行 `android:windowSoftInputMode="adjustPan"`,它现在可以正常工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    相关资源
    最近更新 更多