【问题标题】:React Native Web: how do you center text?React Native Web:如何使文本居中?
【发布时间】:2020-01-20 17:33:19
【问题描述】:

我正在学习 React Native Web。 我一直试图在我的网页上将文本居中,我尝试了来自各种帖子的许多建议,但文本“我的名字是......他的名字是......”仍然卡在网页的左上角无论我在容器中添加/更改哪些属性。另一方面,按钮是居中的。

感谢您的帮助

代码

import React, { useState } from "react"
import { StyleSheet, Text, View, Button } from "react-native"

export default function App() {
    const [name, setName] = useState('Joe');
    const [person, setPerson] = useState({ name: 'mario', age: 40})

    const clickHandler = () => {
        setName('chun-li');
        setPerson({name: 'luigi', age: 45})
    }   

    return (
        <View style={styles.container}>
            <View style={styles.header}>
                <Text >My name is {name}</Text>
                <Text >His name is {person.name} and his age is {person.age}</Text>
            </View>
            <View style={styles.buttonContainer}>
                <Button title='update state' onPress={clickHandler}/>
            </View> 
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        textAlign: 'center',
        textAlignVertical: 'center',
        alignSelf: 'center',
    },

    buttonContainer: {
        alignItems: 'center',
    },

    header: {
        backgroundColor: 'green',
        alignSelf: 'center',
        justifyContent: "flex-start",
        alignItems: 'center',
        top: 0
    }
});

【问题讨论】:

  • 为什么容器是绝对定位的?这使得它的尺寸基本上为 0,没有 top/right/bottom/left 属性。
  • 我没有意识到这一点。我正在尝试各种东西,我刚刚将所有这些东西留在容器中以显示我尝试过的各种属性。我没有一次全部使用它们。我已删除位置:“绝对”,问题仍然存在

标签: react-native expo react-native-web


【解决方案1】:

首先,你需要改变

<View styles={styles.container}>
<View styles={styles.header}>

<View style={styles.container}>
<View style={styles.header}>

最后根据你的要求添加样式更改

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

希望这对您有所帮助。如有疑问,请随意。

【讨论】:

  • 别担心,兄弟。我们都会犯错。
猜你喜欢
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
  • 1970-01-01
  • 2023-04-11
相关资源
最近更新 更多