React Native Web:你如何让文本居中?

React Native Web: how do you center text?

我正在学习 React Native Web。 我一直在尝试将我的网页上的文本居中,我尝试了各种帖子的许多建议,但文本 "my name is...His name is..." 仍然停留在网页的左上角,无论我 add/change 在容器中。另一方面,按钮居中。

感谢您的帮助

代码

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

首先,你需要改变

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

希望对您有所帮助。有疑问欢迎留言。